我试图在数据表对象上执行LINQ查询,奇怪的是,我发现在数据表上执行这样的查询并不简单。例如:
var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
这是不允许的。我怎么才能让这样的东西工作呢?
我很惊讶,LINQ查询不允许在数据表上!
我试图在数据表对象上执行LINQ查询,奇怪的是,我发现在数据表上执行这样的查询并不简单。例如:
var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
这是不允许的。我怎么才能让这样的东西工作呢?
我很惊讶,LINQ查询不允许在数据表上!
当前回答
在我的应用程序中,我发现使用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);
//Create DataTable
DataTable dt= new DataTable();
dt.Columns.AddRange(new DataColumn[]
{
new DataColumn("ID",typeof(System.Int32)),
new DataColumn("Name",typeof(System.String))
});
//Fill with data
dt.Rows.Add(new Object[]{1,"Test1"});
dt.Rows.Add(new Object[]{2,"Test2"});
//Now Query DataTable with linq
//To work with linq it should required our source implement IEnumerable interface.
//But DataTable not Implement IEnumerable interface
//So we call DataTable Extension method i.e AsEnumerable() this will return EnumerableRowCollection<DataRow>
// Now Query DataTable to find Row whoes ID=1
DataRow drow = dt.AsEnumerable().Where(p=>p.Field<Int32>(0)==1).FirstOrDefault();
//
在我的应用程序中,我发现使用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);
你可以像这样通过linq让它优雅地工作:
from prod in TenMostExpensiveProducts().Tables[0].AsEnumerable()
where prod.Field<decimal>("UnitPrice") > 62.500M
select prod
或者像动态linq这样(AsDynamic直接在DataSet上调用):
TenMostExpensiveProducts().AsDynamic().Where (x => x.UnitPrice > 62.500M)
我更喜欢最后一种方法,因为它是最灵活的。 附注:不要忘记连接System.Data.DataSetExtensions.dll引用
正如@ch00k所说:
using System.Data; //needed for the extension methods to work
...
var results =
from myRow in myDataTable.Rows
where myRow.Field<int>("RowNo") == 1
select myRow; //select the thing you want, not the collection
您还需要向System.Data.DataSetExtensions添加一个项目引用