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

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

PK Col1 Col2 1 AB 2 AB 3 CC 4 CC 

我想要一个回报:

 PK Col1 Col2 1 AB 3 CC 

我尝试了下面的代码,但它不起作用:

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

DataTableSelect方法仅支持像{field} = {value}这样的简单过滤表达式。 它不支持复杂的表达式,更不用说SQL / Linq语句了。

但是,您可以使用Linq扩展方法提取DataRow集合,然后创建新的 DataTable

 dt = dt.AsEnumerable() .GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]}) .Select(g => g.OrderBy(r => r["PK"]).First()) .CopyToDataTable(); 
 dt = dt.AsEnumerable().GroupBy(r => r.Field("ID")).Select(g => g.First()).CopyToDataTable(); 

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

此解决方案按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); 
 dt.AsEnumerable() .GroupBy(r => new { Col1 = r["Col1"], Col2 = r["Col2"] }) .Select(g => { var row = dt.NewRow(); row["PK"] = g.Min(r => r.Field("PK")); row["Col1"] = g.Key.Col1; row["Col2"] = g.Key.Col2; return row; }) .CopyToDataTable();