LINQ query on a DataTable

前端 未结 23 1433
执笔经年
执笔经年 2020-11-22 01:59

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:

23条回答
  •  别那么骄傲
    2020-11-22 02:04

    //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
    
    
    // Now Query DataTable to find Row whoes ID=1
    
    DataRow drow = dt.AsEnumerable().Where(p=>p.Field(0)==1).FirstOrDefault();
     // 
    

提交回复
热议问题