LINQ query on a DataTable

前端 未结 23 1435
执笔经年
执笔经年 2020-11-22 01:59

I\'m trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:

23条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 02:09

    In my application I found that using LINQ to Datasets with the AsEnumerable() extension for DataTable as suggested in the answer was extremely slow. If you're interested in optimizing for speed, use James Newtonking's Json.Net library (http://james.newtonking.com/json/help/index.html)

    // Serialize the DataTable to a json string
    string serializedTable = JsonConvert.SerializeObject(myDataTable);    
    Jarray dataRows = Jarray.Parse(serializedTable);
    
    // Run the LINQ query
    List results = (from row in dataRows
                        where (int) row["ans_key"] == 42
                        select row).ToList();
    
    // If you need the results to be in a DataTable
    string jsonResults = JsonConvert.SerializeObject(results);
    DataTable resultsTable = JsonConvert.DeserializeObject(jsonResults);
    

提交回复
热议问题