Mr doubt
Mr doubt

Reputation: 65

LINQ Group by with where condition in Data table using C# asp.net

I am very new in LINQ and trying group by with where condition.

Below is my code working fine without where condition.

 List<DataTable> result = dt.AsEnumerable()
      .GroupBy(x => x.Field<int>("row_Id")) 
      .Select(grp => grp.CopyToDataTable())
      .ToList();

In my datatable dt getting this data.

 row_id         name
  0              Mazhar
  0              Raj
  1              Khan
  1              Ravi

I need to separate row_id=0 and row_id=1 data.

Upvotes: 1

Views: 4156

Answers (2)

D3ivid
D3ivid

Reputation: 61

        var result = dt.Rows.Cast<DataRow>( )
                            .Select( x => new { ID = x.ItemArray[0], ROW = x } )
                            .GroupBy( x => (string)x.ID )
                            .ToList( );

This LINQ separates row_id = 0 to row_id = 1. If you need a iEnumerable of DataRow:

        var result0 = result.Where( x => (string)x.Key == "0" ).FirstOrDefault( ).Select( x => x.ROW ).ToList( );
        var result1 = result.Where( x => (string)x.Key == "1" ).FirstOrDefault( ).Select( x => x.ROW ).ToList( );

Upvotes: 0

Bob K
Bob K

Reputation: 480

The .Where clause below would filter results where rowId = 0.

List<DataTable> result = dt.AsEnumerable()
  .Where(w => w.Field<int>("row_Id") == 0)
  .GroupBy(x => x.Field<int>("row_Id")) 
  .Select(grp => grp.CopyToDataTable())
  .ToList();

Upvotes: 1

Related Questions