1

I have a datatable like the following

A  |  B
-------
1  |  b1
1  |  b2
1  |  b3
2  |  b4
2  |  b5
3  |  b6
3  |  b7
3  |  b8
3  |  b9

How can I write a LINQ command to select the first row on each distinct value on column A:

A  |  B
---------
1  |  b1
2  |  b4
3  |  b6
Siyavash
  • 452
  • 1
  • 5
  • 13

4 Answers4

4
var result = list.GroupBy(x => x.A).Select(x => x.First()).ToList();

or use DistinctBy from MoreLINQ

var result = list.DistinctBy(x => x.A).ToList();
Zen
  • 244
  • 1
  • 3
  • 15
  • what is that list before GroupBy? – Siyavash Sep 05 '12 at 09:24
  • 1
    @Siyavash 'list' is a collection of objects containing field A. In this context, it is a collection of table rows with fields A and B. – Zen Sep 05 '12 at 10:28
  • oh I see, But I think you need to clearly mention that when you are writing your code as the answer. it might cause misunderstanding. – Siyavash Sep 06 '12 at 06:49
3
IEnumerable<DataRow> aRows = table.AsEnumerable()
                                  .GroupBy(r => r.Field<int>("A"))
                                  .Select(g => g.First());

If you want it to be ordered by the B-field (if it isn't ordered by it inititally):

IEnumerable<DataRow> aRows = table.AsEnumerable()
                                  .OrderBy(r => r.Field<String>("B"))
                                  .GroupBy(r => r.Field<int>("A"))
                                  .Select(g => g.First());

If you want another table from it:

DataTable tblARows = aRows.CopyToDataTable();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

You need to group by column A then select the first entry of B. (You may want to sort your B-column values)

There's a code sample here:

Get distinct records using linq to entity

Community
  • 1
  • 1
konqi
  • 5,137
  • 3
  • 34
  • 52
1
var dt = new DataTable();
//init your datatable
var dist = dt.Rows.Cast<DataRow>().GroupBy(r=>r.A).Select(g=>g.First()).ToArray();
Kirill Bestemyanov
  • 11,946
  • 2
  • 24
  • 38