C# 对数据表的 LINQ 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-07-31 17:37:04  来源:igfitidea点击:

LINQ query on a DataTable

提问by Calanus

I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:

我正在尝试对 DataTable 对象执行 LINQ 查询,但奇怪的是我发现在 DataTables 上执行此类查询并不简单。例如:

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

This is not allowed. How do I get something like this working?

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

I'm amazed that LINQ queries are not allowed on DataTables!

我很惊讶在 DataTables 上不允许 LINQ 查询!

采纳答案by Collin K

You can't query against the DataTable's Rowscollection, since DataRowCollectiondoesn't implement IEnumerable<T>. You need to use the AsEnumerable()extension for DataTable. Like so:

您无法对查询DataTable集,因为DataRowCollection没有实现IEnumerable<T>。您需要将AsEnumerable()扩展名用于DataTable. 像这样:

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

And as @Keithsays, you'll need to add a reference to System.Data.DataSetExtensions

正如@Keith所说,您需要添加对System.Data.DataSetExtensions的引用

AsEnumerable()returns IEnumerable<DataRow>. If you need to convert IEnumerable<DataRow>to a DataTable, use the CopyToDataTable()extension.

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

Below is query with Lambda Expression,

下面是使用 Lambda 表达式的查询,

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

回答by Jon Limjap

It's not that they were deliberately not allowed on DataTables, it's just that DataTables pre-date the IQueryable and generic IEnumerable constructs on which Linq queries can be performed.

并不是故意不允许在 DataTables 上使用它们,只是 DataTables 早于可以执行 Linq 查询的 IQueryable 和通用 IEnumerable 构造。

Both interfaces require some sort type-safety validation. DataTables are not strongly typed. This is the same reason why people can't query against an ArrayList, for example.

这两个接口都需要某种类型安全验证。数据表不是强类型的。例如,这与人们无法查询 ArrayList 的原因相同。

For Linq to work you need to map your results against type-safe objects and query against that instead.

为了让 Linq 正常工作,您需要将结果映射到类型安全的对象,然后对其进行查询。

回答by David Wengier

You can use LINQ to objects on the Rows collection, like so:

您可以使用 LINQ to Rows 集合上的对象,如下所示:

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

回答by Keith

As @ch00k said:

正如@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

You also need to add a project reference to System.Data.DataSetExtensions

您还需要添加一个项目引用 System.Data.DataSetExtensions

回答by JoelFan

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

回答by Ravi

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")                         
                    };

the name and age fields are now part of the query object and can be accessed like so: Console.WriteLine(query.name);

name 和 age 字段现在是查询对象的一部分,可以像这样访问:Console.WriteLine(query.name);

回答by Salim

Using LINQ to manipulate data in DataSet/DataTable

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

回答by sushil pandey

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

回答by midhun sankar

Try this

尝试这个

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

回答by Abdul Saboor

For VB.NET The code will look like this:

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

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