LINQ对DataTable的查询

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

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

这是不允许的。 我如何得到这样的工作?

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

因为DataRowCollection没有实现IEnumerable<T> ,所以无法对DataTableRows集合进行查询。 您需要为DataTable使用AsEnumerable()扩展。 像这样:

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

正如Keith所说的,你需要添加一个对System.Data.DataSetExtensions的引用

AsEnumerable()返回IEnumerable<DataRow> 。 如果您需要将IEnumerable<DataRow>转换为DataTable ,请使用CopyToDataTable()扩展。

 var results = from DataRow myRow in myDataTable.Rows where (int)myRow["RowNo"] == 1 select myRow 

这并不是说DataTables是故意不允许在DataTable上使用的,只是DataTable会预先logging可以执行Linq查询的IQueryable和genericsIEnumerable结构。

这两个接口都需要一些types安全validation。 数据表不是强types的。 例如,这就是人们无法查询ArrayList的原因。

对于Linq的工作,你需要将你的结果映射到types安全的对象,然后进行查询。

正如@ 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的项目引用

 var query = from p in dt.AsEnumerable() where p.Field<string>("code") == this.txtCat.Text select new { name = p.Field<string>("name"), age= p.Field<int>("age") }; 

使用LINQ来处理DataSet / DataTable中的数据

 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 ie 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来处理Rows集合中的对象,如下所示:

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

我意识到这已经被回答了几次,但只是提供了另一种方法,我喜欢使用.Cast<T>()方法,它帮助我保持清晰的types定义,并深深的思想保持清醒.AsEnumerable()无论如何调用它:

  var results = from myRow in myDataTable.Rows.Cast<DataRow>() where myRow.Field<int>("RowNo") == 1 select myRow; 

要么

  var results = myDataTable.Rows.Cast<DataRow>() .FirstOrDefault(x => x.Field<int>("RowNo") == 1); 

试试这个简单的查询行:

 var result=myDataTable.AsEnumerable().Where(myRow => myRow.Field<int>("RowNo") == 1); 

希望它有帮助;

尝试这个

 var row = (from result in dt.AsEnumerable().OrderBy( result => Guid.NewGuid()) select result).Take(3) ; 

最有可能的是,DataSet,DataTable和DataRow的类已经在解决scheme中定义了。 如果是这种情况,您将不需要DataSetExtensions引用。

防爆。 DataSet类名 – > CustomSet,DataRow类名 – > 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); 

快乐的编码!

这是一个简单的方法,适用于我并使用lambdaexpression式:

 var results = myDataTable.Select("").FirstOrDefault(x => (int)x["RowNo"] == 1) 

那么如果你想要一个特定的值:

 if(results != null) var foo = results["ColName"].ToString() 
 var results = from myRow in myDataTable where results.Field<Int32>("RowNo") == 1 select results; 

对于VB.NET代码将如下所示:

 Dim results = From myRow In myDataTable Where myRow.Field(Of Int32)("RowNo") = 1 Select myRow 

在我的应用程序中,我发现在答案中使用LINQ to Datasets和AsEnumerable()扩展DataTable是非常缓慢的。 如果您有兴趣优化速度,请使用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 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); 
 IEnumerable<string> result = from myRow in dataTableResult.AsEnumerable() select myRow["server"].ToString() ; 

你可以像这样通过linq获得优雅的工作:

 from prod in TenMostExpensiveProducts().Tables[0].AsEnumerable() where prod.Field<decimal>("UnitPrice") > 62.500M select prod 

或者像dynamicLINQ这样(在DataSet上直接调用AsDynamic):

 TenMostExpensiveProducts().AsDynamic().Where (x => x.UnitPrice > 62.500M) 

我更喜欢最后的方法,而最灵活的是。 PS:不要忘记连接System.Data.DataSetExtensions.dll参考

尝试这个…

 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<String>( dt.Columns[1] ); foreach( var name in names ) { Console.WriteLine( name ); } 

关于如何实现这个的例子如下所示:

 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();