首页 文章

关于DataTable的LINQ查询

提问于
浏览
919

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

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

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

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

21 回答

  • 8

    这是一个适合我并使用lambda表达式的简单方法:

    var results = myDataTable.Select("").FirstOrDefault(x => (int)x["RowNo"] == 1)
    

    然后,如果你想要一个特定的 Value :

    if(results != null) 
        var foo = results["ColName"].ToString()
    
  • 4

    你可以通过这样的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)
    

    我更喜欢最后一种方法,而最灵活的方法 . P.S . :不要忘记连接 System.Data.DataSetExtensions.dll 参考

  • 35

    试试这个

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

    有关如何实现此目的的示例如下:

    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();
    
  • 14

    试试这个...

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

    试试这个简单的查询行:

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

    我意识到这已经被回答了几次,但只是为了提供另一种方法,我喜欢使用 .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);
    
  • 24

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

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

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

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

    并不是因为DataTables故意不允许它们,只是DataTables可以在可以执行Linq查询的IQueryable和通用IEnumerable构造之前预定 .

    两个接口都需要一些排序类型安全验证 . DataTables不是强类型的 . 这就是人们无法查询ArrayList的原因 .

    要使Linq工作,您需要将结果映射到类型安全的对象,并对其进行查询 .

  • 1158

    Using LINQ to manipulate data in 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();
    
  • 25

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

  • 2
    var results = from myRow in myDataTable
    where results.Field<Int32>("RowNo") == 1
    select results;
    
  • 3

    你可以试试这个,但你必须确定每个列的值的类型

    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"),    
    });
    
  • 8
    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")                         
                        };
    
  • 2

    您无法查询 DataTable 的Rows集合,因为 DataRowCollection 未实现 IEnumerable<T> . 您需要为 DataTable 使用 AsEnumerable() 扩展名 . 像这样:

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

    正如基思所说,你需要添加对System.Data.DataSetExtensions的引用

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

  • 20
    IEnumerable<string> result = from myRow in dataTableResult.AsEnumerable()
                                 select myRow["server"].ToString() ;
    
  • 46

    在我的应用程序中,我发现在答案中建议使用LINQ to Datasets和DataTable的AsEnumerable()扩展非常慢 . 如果你're interested in optimizing for speed, use 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);
    

相关问题