我试图在数据表对象上执行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查询不允许在数据表上!
当前回答
您可以尝试这样做,但必须确定每个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"),
});
其他回答
在我的应用程序中,我发现使用LINQ到数据集的AsEnumerable()扩展数据表,如答案中所建议的是非常慢的。如果你对优化速度感兴趣,可以使用James Newtonking的Json。网上图书馆(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);
正如@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添加一个项目引用
试试这个…
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这样(AsDynamic直接在DataSet上调用):
TenMostExpensiveProducts().AsDynamic().Where (x => x.UnitPrice > 62.500M)
我更喜欢最后一种方法,因为它是最灵活的。 附注:不要忘记连接System.Data.DataSetExtensions.dll引用
我提出以下解决方案:
DataView view = new DataView(myDataTable);
view.RowFilter = "RowNo = 1";
DataTable results = view.ToTable(true);
查看DataView文档,我们首先看到的是:
表示数据表的可数据化、自定义视图,用于排序、过滤、搜索、编辑和导航。
我从中得到的是,DataTable仅用于存储数据,而DataView则允许我们对DataTable进行“查询”。
下面是这个特殊情况下的工作原理:
您尝试实现SQL语句
SELECT *
FROM myDataTable
WHERE RowNo = 1
“数据表语言”。在c#中,我们可以这样读:
FROM myDataTable
WHERE RowNo = 1
SELECT *
在c#中是这样的:
DataView view = new DataView(myDataTable); //FROM myDataTable
view.RowFilter = "RowNo = 1"; //WHERE RowNo = 1
DataTable results = view.ToTable(true); //SELECT *