0

I have a Dataset that contains e.g. id, date, other fields...

enter image description here

I want to retrieve unique rows based on ids and latest date.

I have this query but I can't figure out where to put the date condition.

DataTable dt = ds.Tables[0]
                     .AsEnumerable()
                     .GroupBy(row => row.Field<string>("id"))
                     .Select(group => group.First())
                     .CopyToDataTable();

r.Text = dt.Rows.Count.ToString();

gv.DataSource = dt;
gv.DataBind();

The result should be

1 - 8/2/2014
2 - 1/8/2014
4 - 1/2/2011

Thanks,

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Benk
  • 1,284
  • 6
  • 33
  • 64

2 Answers2

2

You need to do OrderByDescending for Date Field and then select First:

 .Select(group => group.OrderByDescending(r=> r.Field<DateTime>("Date")).First())

So your query would be:

DataTable dt = ds.Tables[0].AsEnumerable()
                .GroupBy(row => row.Field<string>("id"))
                .Select(group => group
                                .OrderByDescending(r=> r.Field<DateTime>("Date"))
                                .First())
                .CopyToDataTable();
Habib
  • 219,104
  • 29
  • 407
  • 436
0

Maybe you can use this: LINQ to Datatable Group by and return all columns

And only return the field that you want, p.e. date

Community
  • 1
  • 1