[英]LINQ query on a DataTable
我正在尝试对数据表 object 执行 LINQ 查询,奇怪的是我发现对数据表执行此类查询并不简单。 例如:
var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
这是不允许的。 我怎样才能得到这样的工作?
我很惊讶 DataTables 不允许 LINQ 查询!
您不能查询DataTable
的Rows集合,因为DataRowCollection
没有实现IEnumerable<T>
。 您需要为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()
扩展。
下面是使用 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
并不是故意不允许在 DataTables 上使用它们,只是 DataTables 早于可以执行 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")
};
name 和 age 字段现在是查询对象的一部分,可以像这样访问: Console.WriteLine(query.name);
我意识到这已经回答了几次,但只是提供另一种方法:
我喜欢使用.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);
如评论中所述,不需要System.Data.DataSetExtensions
或任何其他程序集( 参考)
使用 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 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 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;
这是一种适用于我并使用 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<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)
我更喜欢最后一种方法,而它是最灵活的。 PS:不要忘记连接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"),
});
//Json Formating code
//DT is DataTable
var filter = (from r1 in DT.AsEnumerable()
//Grouping by multiple columns
group r1 by new
{
EMPID = r1.Field<string>("EMPID"),
EMPNAME = r1.Field<string>("EMPNAME"),
} into g
//Selecting as new type
select new
{
EMPID = g.Key.EMPID,
MiddleName = g.Key.EMPNAME});
我提出以下解决方案:
DataView view = new DataView(myDataTable);
view.RowFilter = "RowNo = 1";
DataTable results = view.ToTable(true);
查看DataView Documentation ,我们可以看到的第一件事是:
表示用于排序、筛选、搜索、编辑和导航的 DataTable 的可绑定数据的自定义视图。
我从中得到的是,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 *
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.