2013-10-16 17 views
10

我嘗試通過從每個組中選擇第一行來刪除重複的行。 對於實例如何在DataTable.Select(Expression)中使用SELECT GROUP BY?

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

你不能。改用LINQ。 – SLaks

+0

你不能通過PK字段進行分組... – Baral

+0

我想用什麼,但是我想返回一個DataTable對象。 –

回答

22

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

您需要使用什麼彙編參考才能使其發揮作用。我正在使用System.data,但GroupBy命令聲明我缺少程序集引用。 – user5013

+0

這是什麼擴展名.CopyToDataTable()? –

+1

@SebastianWidz ['System.Data.DataSetExtensions'](https://msdn.microsoft.com/en-us/library/bb396189(v = vs.110).aspx) –

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

這是什麼擴展名.CopyToDataTable()? –

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

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