LINQ query on a DataTable

前端 未结 23 1301
执笔经年
执笔经年 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:21
    IEnumerable<string> result = from myRow in dataTableResult.AsEnumerable()
                                 select myRow["server"].ToString() ;
    
    0 讨论(0)
  • 2020-11-22 02:21

    Try this...

    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 );
    }
    
    0 讨论(0)
  • 2020-11-22 02:25
    var results = from myRow in myDataTable
    where results.Field<Int32>("RowNo") == 1
    select results;
    
    0 讨论(0)
  • 2020-11-22 02:25
                        //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});
    
    0 讨论(0)
  • 2020-11-22 02:26

    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.

    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.

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

    0 讨论(0)
  • 2020-11-22 02:26

    Try this

    var row = (from result in dt.AsEnumerable().OrderBy( result => Guid.NewGuid()) select result).Take(3) ; 
    
    0 讨论(0)
提交回复
热议问题