30

I try to remove the duplicate rows by select a first row from every group. For Example

PK     Col1     Col2
1        A        B
2        A        B
3        C        C
4        C        C

I want a return:

PK     Col1     Col2
1        A        B
3        C        C

I tried following code but it didn't work:

DataTable dt = GetSampleDataTable(); //Get the table above.
dt = dt.Select("SELECT MIN(PK), Col1, Col2 GROUP BY Col1, Col2);
5
  • You can't. Use LINQ instead.
    – SLaks
    Commented Oct 16, 2013 at 15:24
  • 1
    You must not group by the PK field...
    – Baral
    Commented Oct 16, 2013 at 15:26
  • I would like to use whatever, but I want to return a DataTable object. Commented Oct 16, 2013 at 15:27
  • Why not delegate grouping or other complex processing to sql at database level which would be more natural place
    – Siddhartha
    Commented Feb 8, 2020 at 19:03
  • Does this answer your question? Efficient DataTable Group By
    – JJS
    Commented Aug 22, 2020 at 15:39

5 Answers 5

64

DataTable's Select method only supports simple filtering expressions like {field} = {value}. It does not support complex expressions, let alone SQL/Linq statements.

You can, however, use Linq extension methods to extract a collection of DataRows then create a new DataTable.

dt = dt.AsEnumerable()
       .GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
       .Select(g => g.OrderBy(r => r["PK"]).First())
       .CopyToDataTable();
6
  • 1
    What assembly reference do you need to use in order to get this to work. I am using System.data but the GroupBy command is stating I am missing an assembly reference.
    – user5013
    Commented Feb 22, 2016 at 20:15
  • What extension is this .CopyToDataTable() ? Commented Nov 23, 2016 at 8:20
  • 2
    @SebastianWidz System.Data.DataSetExtensions
    – D Stanley
    Commented Nov 23, 2016 at 14:47
  • @user5013 GroupBy is in the System.Linq namespace. You need a reference to System.Core if you don't have one already.
    – D Stanley
    Commented Nov 23, 2016 at 14:48
  • How to use having clause in this?
    – Vahid
    Commented Jul 26, 2023 at 8:06
8
dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();
1
  • 1
    What extension is this .CopyToDataTable() ? Commented Nov 23, 2016 at 8:20
7
dt.AsEnumerable()
    .GroupBy(r => new { Col1 = r["Col1"], Col2 = r["Col2"] })
    .Select(g =>
    {
        var row = dt.NewRow();

        row["PK"] = g.Min(r => r.Field<int>("PK"));
        row["Col1"] = g.Key.Col1;
        row["Col2"] = g.Key.Col2;

        return row;

    })
    .CopyToDataTable();
0

This solution sort by Col1 and group by Col2. Then extract value of Col2 and display it in a mbox.

var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string x = "";
foreach (var k in grouped) x += (string)(k.ElementAt(0)["Col2"]) + Environment.NewLine;
MessageBox.Show(x);
-1

Based on @Alfred Wallace's solution :

        DataTable dt = new DataTable();
        dt.Columns.Add("Col1");
        dt.Columns.Add("Col2");

        dt.Rows.Add("120", "34");
        dt.Rows.Add("121", "34");
        dt.Rows.Add("122", "34");

        dt.Rows.Add("1", "345");
        dt.Rows.Add("2", "345");
        dt.Rows.Add("3", "345");

        var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
        string xxx = "", yyy = "";
        foreach (var k_group in grouped)
        {                
            xxx += (string)(k_group.ElementAt(0)["Col1"]) + Environment.NewLine;
            foreach (DataRow item_dr in k_group)
            {                    
                yyy += (string)(item_dr["Col1"]) + Environment.NewLine;
                //  or use WhatEverMethod(item_dr);
            }
            var zzz = k_group.Max(g => g["Col1"]);
            var qqq = k_group.Key;
        }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.