我正在尝试对DataTable对象执行LINQ查询,奇怪的是我发现在DataTables上执行此类查询并不简单.例如:
var results = from myRow in myDataTable where results.Field("RowNo") == 1 select results;
这是不允许的.我如何得到这样的工作?
我很惊讶DataTables上不允许LINQ查询!
你不能查询DataTable
's Rows集合,因为DataRowCollection
没有实现IEnumerable
.您需要使用AsEnumerable()
扩展名DataTable
.像这样:
var results = from myRow in myDataTable.AsEnumerable() where myRow.Field("RowNo") == 1 select myRow;
正如Keith所说,您需要添加对System.Data.DataSetExtensions的引用
AsEnumerable()
回报IEnumerable
.如果您需要转换IEnumerable
为a DataTable
,请使用CopyToDataTable()
扩展名.
下面是Lambda Expression的查询,
var result = myDataTable .AsEnumerable() .Where(myRow => myRow.Field("RowNo") == 1);
var results = from DataRow myRow in myDataTable.Rows where (int)myRow["RowNo"] == 1 select myRow
并不是故意不允许在DataTables上使用它们,只是DataTables会在可以执行Linq查询的IQueryable和通用IEnumerable构造之前进行预定.
两个接口都需要某种类型安全验证.DataTables不是强类型的.例如,这与人们无法查询ArrayList的原因相同.
要使Linq工作,您需要将结果映射到类型安全的对象,并对其进行查询.
正如@ ch00k所说:
using System.Data; //needed for the extension methods to work ... var results = from myRow in myDataTable.Rows where myRow.Field("RowNo") == 1 select myRow; //select the thing you want, not the collection
您还需要添加项目引用 System.Data.DataSetExtensions
var query = from p in dt.AsEnumerable() where p.Field("code") == this.txtCat.Text select new { name = p.Field ("name"), age= p.Field ("age") };
我意识到这已经回答了几次,但只是为了提供另一种方法,我喜欢使用这种.Cast
方法,它帮助我保持理智,看到定义的显式类型,并且.AsEnumerable()
内心深处我认为无论如何都要调用它:
var results = from myRow in myDataTable.Rows.Cast()
where myRow.Field("RowNo") == 1 select myRow;
要么
var results = myDataTable.Rows.Cast()
.FirstOrDefault(x => x.Field("RowNo") == 1);
使用LINQ来操作DataSet/DataTable中的数据
var results = from myRow in tblCurrentStock.AsEnumerable() where myRow.Field("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// Now Query DataTable to find Row whoes ID=1 DataRow drow = dt.AsEnumerable().Where(p=>p.Field (0)==1).FirstOrDefault(); //
试试这个简单的查询行:
var result=myDataTable.AsEnumerable().Where(myRow => myRow.Field("RowNo") == 1);
您可以在Rows集合上使用LINQ到对象,如下所示:
var results = from myRow in myDataTable.Rows where myRow.Field("RowNo") == 1 select myRow;
这是一个适合我并使用lambda表达式的简单方法:
var results = myDataTable.Select("").FirstOrDefault(x => (int)x["RowNo"] == 1)
然后,如果你想要一个特定的价值:
if(results != null) var foo = results["ColName"].ToString()
试试这个
var row = (from result in dt.AsEnumerable().OrderBy( result => Guid.NewGuid()) select result).Take(3) ;
最有可能的是,DataSet,DataTable和DataRow的类已在解决方案中定义.如果是这种情况,您将不需要DataSetExtensions参考.
防爆.DataSet类名 - > CustomSet,DataRow类名 - > CustomTableRow(具有已定义的列:RowNo,...)
var result = from myRow in myDataTable.Rows.OfType() where myRow.RowNo == 1 select myRow;
或者(我更喜欢)
var result = myDataTable.Rows.OfType().Where(myRow => myRow.RowNo);
var results = from myRow in myDataTable where results.Field("RowNo") == 1 select results;
在我的应用程序中,我发现在答案中建议使用LINQ to Datasets和DataTable的AsEnumerable()扩展非常慢.如果您对优化速度感兴趣,请使用James Newtonking的Json.Net库(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 Listresults = (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);
关于如何实现此目的的示例如下:
DataSet dataSet = new DataSet(); //Create a dataset dataSet = _DataEntryDataLayer.ReadResults(); //Call to the dataLayer to return the data //LINQ query on a DataTable var dataList = dataSet.Tables["DataTable"] .AsEnumerable() .Select(i => new { ID = i["ID"], Name = i["Name"] }).ToList();
对于VB.NET代码如下所示:
Dim results = From myRow In myDataTable Where myRow.Field(Of Int32)("RowNo") = 1 Select myRow
试试这个...
SqlCommand cmd = new SqlCommand( "Select * from Employee",con); SqlDataReader dr = cmd.ExecuteReader( ); DataTable dt = new DataTable( "Employee" ); dt.Load( dr ); var Data = dt.AsEnumerable( ); var names = from emp in Data select emp.Field( dt.Columns[1] ); foreach( var name in names ) { Console.WriteLine( name ); }
IEnumerableresult = from myRow in dataTableResult.AsEnumerable() select myRow["server"].ToString() ;
你可以通过这样的linq让它变得优雅:
from prod in TenMostExpensiveProducts().Tables[0].AsEnumerable() where prod.Field("UnitPrice") > 62.500M select prod
或者像动态linq这样(AsDynamic直接在DataSet上调用):
TenMostExpensiveProducts().AsDynamic().Where (x => x.UnitPrice > 62.500M)
我更喜欢最后一种方法,而且最灵活.PS:别忘了连接System.Data.DataSetExtensions.dll
参考
您可以尝试这样做,但是必须确保每个列的值类型
Listresult = myDataTable.AsEnumerable().Select(x=> new MyClass(){ Property1 = (string)x.Field ("ColumnName1"), Property2 = (int)x.Field ("ColumnName2"), Property3 = (bool)x.Field ("ColumnName3"), });