如何在DataTable.Select(Expression)中使用SELECT GROUP BY?

时间:2013-10-16 15:22:57

标签: c# datatable duplicates

我尝试通过从每个组中选择第一行来删除重复的行。 例如

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

我想要一个回报:

PK     Col1     Col2
1        A        B
3        C        C

我尝试了以下代码,但它没有工作:

DataTable dt = GetSampleDataTable(); //Get the table above.
dt = dt.Select("SELECT MIN(PK), Col1, Col2 GROUP BY Col1, Col2);

5 个答案:

答案 0 :(得分:34)

DataTable的{​​{1}}方法仅支持Select等简单过滤表达式。它不支持复杂的表达式,更不用说SQL / Linq语句了。

但是,您可以使用Linq扩展方法提取{field} = {value}的集合,然后创建 new DataRow

DataTable

答案 1 :(得分:6)

dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

答案 2 :(得分:4)

Tim Schmelter回答https://stackoverflow.com/a/8472044/26877

public DataTable GroupBy(string i_sGroupByColumn, string i_sAggregateColumn, DataTable i_dSourceTable)
{

    DataView dv = new DataView(i_dSourceTable);

    //getting distinct values for group column
    DataTable dtGroup = dv.ToTable(true, new string[] { i_sGroupByColumn });

    //adding column for the row count
    dtGroup.Columns.Add("Count", typeof(int));

    //looping thru distinct values for the group, counting
    foreach (DataRow dr in dtGroup.Rows) {
        dr["Count"] = i_dSourceTable.Compute("Count(" + i_sAggregateColumn + ")", i_sGroupByColumn + " = '" + dr[i_sGroupByColumn] + "'");
    }

    //returning grouped/counted result
    return dtGroup;
}

示例:

DataTable desiredResult = GroupBy("TeamID", "MemberID", dt);

答案 3 :(得分:1)

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();

答案 4 :(得分:0)

此解决方案按Col1排序,按Col2排序。然后提取Col2的值并将其显示在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);