我试图在数据表对象上执行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查询不允许在数据表上!
当前回答
正如@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添加一个项目引用
其他回答
您可以尝试这样做,但必须确定每个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"),
});
我知道这个问题已经被回答过很多次了,但我只想提供另一种方法:
我喜欢使用.Cast<T>()方法,它可以帮助我在看到定义的显式类型时保持理智,并且我认为.AsEnumerable()无论如何都会调用它:
var results = from myRow in myDataTable.Rows.Cast<DataRow>()
where myRow.Field<int>("RowNo") == 1 select myRow;
or
var results = myDataTable.Rows.Cast<DataRow>()
.FirstOrDefault(x => x.Field<int>("RowNo") == 1);
如注释中所述,不需要System.Data.DataSetExtensions或任何其他程序集(参考)
你可以像这样通过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引用
使用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();
//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();
//