我正在尝试对数据表对象执行LINQ查询,奇怪的是,我发现对数据表执行此类查询并不简单。例如:
1 2 3
| var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results; |
这是不允许的。我怎样才能得到这样的工作?
我很惊讶Linq查询不允许出现在数据表上!
不能查询DataTable的行集合,因为DataRowCollection不实现IEnumerable。您需要对DataTable使用AsEnumerable()扩展。像这样:
1 2 3
| var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow; |
正如Keith所说,您需要添加对System.Data.DataSetTextensions的引用。
AsEnumerable()返回IEnumerable。如果需要将IEnumerable转换为DataTable,请使用CopyToDataTable()扩展。
下面是使用lambda表达式的查询,
1 2 3
| var result = myDataTable
.AsEnumerable()
.Where(myRow => myRow.Field<int>("RowNo") == 1); |
1 2 3
| var results = from DataRow myRow in myDataTable.Rows
where (int)myRow["RowNo"] == 1
select myRow |
并不是故意不允许在数据表上使用它们,而是数据表预先为可以执行LINQ查询的iQueryable和泛型IEnumerable构造指定了日期。
两个接口都需要某种类型的安全验证。数据表不是强类型的。例如,这也是人们不能查询ArrayList的原因。
要使Linq正常工作,您需要将结果映射到类型安全的对象,并针对该对象进行查询。
正如@ CH00 K所说:
1 2 3 4 5 6 7 8
| 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的项目引用。
1 2 3 4 5 6 7
| 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()方法,它有助于我在看到定义的显式类型时保持清醒,在内心深处,我认为.AsEnumerable()无论如何都称之为:
1 2
| var results = from myRow in myDataTable.Rows.Cast<DataRow>()
where myRow.Field<int>("RowNo") == 1 select myRow; |
或
1 2
| var results = myDataTable.Rows.Cast<DataRow>()
.FirstOrDefault(x => x.Field<int>("RowNo") == 1); |
使用LINQ操作数据集/数据表中的数据
1 2 3 4
| var results = from myRow in tblCurrentStock.AsEnumerable()
where myRow.Field<string>("item_name").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())
select myRow;
DataView view = results.AsDataView(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| //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();
// |
尝试以下简单的查询行:
1
| var result=myDataTable.AsEnumerable().Where(myRow => myRow.Field<int>("RowNo") == 1); |
可以使用"行"集合上的Linq to对象,例如:
1
| var results = from myRow in myDataTable.Rows where myRow.Field("RowNo") == 1 select myRow; |
试试这个
1
| var row = (from result in dt.AsEnumerable().OrderBy( result => Guid.NewGuid()) select result).Take(3) ; |
最有可能的是,解决方案中已经定义了数据集、数据表和数据行的类。如果是这种情况,您将不需要DataSetExtensions引用。
例如,dataset class name->customset,datarow class name->customtablerow(定义了列:rowno,…)
1 2 3
| var result = from myRow in myDataTable.Rows.OfType<CustomSet.CustomTableRow>()
where myRow.RowNo == 1
select myRow; |
或者(我喜欢)
1
| var result = myDataTable.Rows.OfType<CustomSet.CustomTableRow>().Where(myRow => myRow.RowNo); |
这是一种简单的方法,适用于我并使用lambda表达式:
1
| var results = myDataTable.Select("").FirstOrDefault(x => (int)x["RowNo"] == 1) |
如果您想要一个特定的值:
1 2
| if(results != null)
var foo = results["ColName"].ToString() |
1 2 3
| var results = from myRow in myDataTable
where results.Field<Int32>("RowNo") == 1
select results; |
对于vb.net,代码如下:
1 2
| Dim results = From myRow In myDataTable
Where myRow.Field(Of Int32)("RowNo") = 1 Select myRow |
在我的应用程序中,我发现使用linq-to-datasets时,如答案中建议的那样,对datatable使用asEnumerable()扩展名是非常缓慢的。如果您对优化速度感兴趣,请使用james newtonking的json.net库(http://james.newtonking.com/json/help/index.html)。
1 2 3 4 5 6 7 8 9 10 11 12
| // 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); |
1 2
| IEnumerable<string> result = from myRow in dataTableResult.AsEnumerable()
select myRow["server"].ToString() ; |
如何实现这一点的示例如下:
1 2 3 4 5 6 7 8 9 10 11
| 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(); |
试试这个…
1 2 3 4 5 6 7 8 9 10
| 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让它优雅地工作:
1 2 3
| from prod in TenMostExpensiveProducts().Tables[0].AsEnumerable()
where prod.Field<decimal>("UnitPrice") > 62.500M
select prod |
或者像dynamic linq this(asdynamic直接在数据集中调用):
1
| TenMostExpensiveProducts().AsDynamic().Where (x => x.UnitPrice > 62.500M) |
我更喜欢最后一种方法,而最灵活的方法是。P.S.:不要忘记连接System.Data.DataSetExtensions.dll参考
您可以尝试此操作,但必须确保每个列的值类型
24