0

I have a .NET DataTable with the following content:

Date        ID1     ID2
1/1/2014    1       a
1/1/2014    2       a
1/1/2014    3       a
2/1/2014    1       b
2/1/2014    2       b
2/1/2014    3       b
3/1/2014    1       c
3/1/2014    2       c
3/1/2014    3       c

How do I use datatable method to eliminate the duplicates so that it becomes

Date        ID1     ID2
1/1/2014    1       a
2/1/2014    2       b
3/1/2014    3       c
Meidi
  • 562
  • 1
  • 8
  • 28
  • 1
    Possible duplicate http://stackoverflow.com/questions/4415519/best-way-to-remove-duplicate-entries-from-a-data-table – Mike Schwartz Feb 10 '14 at 21:37
  • Duplicate according to what column(s)? If you just want to compare the date, why do you take the first record of the first date, the second record of the second date and the last record of the last date?Is that arbitrary? – Tim Schmelter Feb 10 '14 at 21:42
  • duplicate Date and ID2, maybe I shouldn't call it duplicate... – Meidi Feb 10 '14 at 21:44

1 Answers1

1

So you want to remove "duplicates" of a DataTable according to the date and ID2 columns. You can use Linq-To-DataSet and Enumerable.GroupBy:

tblDate = tblDate.AsEnumerable()
    .GroupBy(r => new { date = r.Field<DateTime>("Date"), id2 = r.Field<string>("ID2") })
    .Select(g => g.First())
    .CopyToDataTable();

This takes simply the first row of each group which is not your result. However, you haven't mentioned the rule for ID1.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939