我试图在数据表对象上执行LINQ查询,奇怪的是,我发现在数据表上执行这样的查询并不简单。例如:

var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;

这是不允许的。我怎么才能让这样的东西工作呢?

我很惊讶,LINQ查询不允许在数据表上!


当前回答

您可以尝试这样做,但必须确定每个Column的值类型

List<MyClass> result = myDataTable.AsEnumerable().Select(x=> new MyClass(){
     Property1 = (string)x.Field<string>("ColumnName1"),
     Property2 = (int)x.Field<int>("ColumnName2"),
     Property3 = (bool)x.Field<bool>("ColumnName3"),    
});

其他回答

您可以尝试这样做,但必须确定每个Column的值类型

List<MyClass> result = myDataTable.AsEnumerable().Select(x=> new MyClass(){
     Property1 = (string)x.Field<string>("ColumnName1"),
     Property2 = (int)x.Field<int>("ColumnName2"),
     Property3 = (bool)x.Field<bool>("ColumnName3"),    
});
var results = from DataRow myRow in myDataTable.Rows
    where (int)myRow["RowNo"] == 1
    select myRow

使用LINQ操作数据集/数据表中的数据

var results = from myRow in tblCurrentStock.AsEnumerable()
              where myRow.Field<string>("item_name").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())
              select myRow;
DataView view = results.AsDataView();

在我的应用程序中,我发现使用LINQ到数据集的AsEnumerable()扩展数据表,如答案中所建议的是非常慢的。如果你对优化速度感兴趣,可以使用James Newtonking的Json。网上图书馆(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<JToken> 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<DataTable>(jsonResults);

在解决方案中很可能已经定义了DataSet、DataTable和DataRow的类。如果是这样的话,就不需要DataSetExtensions引用了。

示例:数据集类名称-> CustomSet,数据流类名称-> CustomTableRow(定义列:RowNo,…)

var result = from myRow in myDataTable.Rows.OfType<CustomSet.CustomTableRow>()
             where myRow.RowNo == 1
             select myRow;

或者(随我喜欢)

var result = myDataTable.Rows.OfType<CustomSet.CustomTableRow>().Where(myRow => myRow.RowNo);