数据表上的 LINQ 查询
题
我正在尝试对 DataTable 对象执行 LINQ 查询,但奇怪的是,我发现对 DataTable 执行此类查询并不简单。例如:
var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
这是不允许的。我怎样才能让这样的东西发挥作用?
我很惊讶 DataTables 上不允许 LINQ 查询!
解决方案
您不能查询 DataTable
的 行数 收藏,自 DataRowCollection
不执行 IEnumerable<T>
. 。您需要使用 AsEnumerable()
扩展为 DataTable
. 。就像这样:
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;
正如基思所说,您需要添加对 系统.数据.数据集扩展
AsEnumerable()
回报 IEnumerable<DataRow>
. 。如果您需要转换 IEnumerable<DataRow>
到一个 DataTable
, , 使用 CopyToDataTable()
扩大。
下面是使用 Lambda 表达式的查询,
var result = myDataTable
.AsEnumerable()
.Where(myRow => myRow.Field<int>("RowNo") == 1);
其他提示
var results = from DataRow myRow in myDataTable.Rows
where (int)myRow["RowNo"] == 1
select myRow
并不是故意不允许在 DataTable 上使用它们,而是 DataTable 提前了可以执行 Linq 查询的 IQueryable 和通用 IEnumerable 构造。
这两个接口都需要某种类型安全验证。数据表不是强类型的。例如,这与人们无法查询 ArrayList 的原因相同。
要使 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
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")
};
我意识到这个问题已经被回答过几次了,但为了提供另一种方法,我喜欢使用 .Cast<T>()
方法,它帮助我在看到定义的显式类型时保持理智,并且在内心深处我认为 .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);
//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();
//
var results = from myRow in tblCurrentStock.AsEnumerable()
where myRow.Field<string>("item_name").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())
select myRow;
DataView view = results.AsDataView();
尝试这个简单的查询行:
var result=myDataTable.AsEnumerable().Where(myRow => myRow.Field<int>("RowNo") == 1);
您可以使用 LINQ to Rows 集合上的对象,如下所示:
var results = from myRow in myDataTable.Rows where myRow.Field("RowNo") == 1 select myRow;
尝试这个
var row = (from result in dt.AsEnumerable().OrderBy( result => Guid.NewGuid()) select result).Take(3) ;
这是一种适合我并使用 lambda 表达式的简单方法:
var results = myDataTable.Select("").FirstOrDefault(x => (int)x["RowNo"] == 1)
那么如果你想要一个特定的值:
if(results != null)
var foo = results["ColName"].ToString()
最有可能的是,DataSet、DataTable 和 DataRow 的类已在解决方案中定义。如果是这种情况,您将不需要 DataSetExtensions 引用。
前任。DataSet类名->CustomSet,DataRow类名->CustomTableRow(具有定义的列:行号,...)
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);
var results = from myRow in myDataTable
where results.Field<Int32>("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
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 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
IEnumerable<string> result = from myRow in dataTableResult.AsEnumerable()
select myRow["server"].ToString() ;
尝试这个...
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 );
}
你可以通过 linq 让它优雅地工作,如下所示:
from prod in TenMostExpensiveProducts().Tables[0].AsEnumerable()
where prod.Field<decimal>("UnitPrice") > 62.500M
select prod
或者像动态 linq 这样(直接在 DataSet 上调用 AsDynamic):
TenMostExpensiveProducts().AsDynamic().Where (x => x.UnitPrice > 62.500M)
我更喜欢最后一种方法,但它是最灵活的。附:不要忘记连接 System.Data.DataSetExtensions.dll
参考
您可以尝试此操作,但必须确定每个列的值的类型
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"),
});