1

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.

5
  • it would be better if you could describe what you are trying to do (rather than what the code should look like) Commented Jul 7, 2018 at 9:55
  • in my dt I am getting data with row_id=0 and row_id=1. So I am trying to separate row_id=0 and row_id=1 data and row_id are fixed in [email protected] Commented Jul 7, 2018 at 9:59
  • I updated my question please check above. @M.kazemAkhgary Commented Jul 7, 2018 at 10:05
  • 2
    Why do you need the where condition? GroupBy does what you explained. Commented Jul 7, 2018 at 10:14
  • List<DataTable> result = dt.AsEnumerable().Where(x => x.Field<int>("row_Id") == 0) .GroupBy(x => x.Field<int>("row_Id")) .Select(grp => grp.CopyToDataTable()) .ToList(); i got my answer from my self.@L_J Commented Jul 7, 2018 at 10:29

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

After the Where the GroupBy does nothing.
What do you want the result to look like after filtering by one of the IDs?
0
        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( );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.