2013-03-04 95 views
-3

我有一個數據表:集團通過DataTable中

DataTable table = new DataTable(); 

table.Columns.Add("Name", typeof(string)); 
table.Columns.Add("Value", typeof(string));   

table.Rows.Add("A", "High"); 
table.Rows.Add("B", "Low"); 
table.Rows.Add("A", "Low"); 
table.Rows.Add("C", "High"); 
table.Rows.Add("B", "Medium"); 
table.Rows.Add("A", "High"); 
table.Rows.Add("A", "High"); 

我想使用LINQ到組我的結果是這樣的:

Name value Count 
------------------- 
A  High 3 
A  Low  1 
B  Medium 1 
B  Low  1 
C  High 1 
+2

您好,歡迎堆棧溢出。很高興聽到你想分組你的桌子......但請記住,這是一個問答網站。你的問題是什麼?你有什麼嘗試,你卡在哪裏? – stakx 2013-03-04 22:21:56

回答

0

這LINQ到數據集查詢將返回分組值的匿名對象

var query = from r in table.AsEnumerable() 
      group r by new { 
       Name = r.Field<string>("Name"), 
       Value = r.Field<string>("Value") 
      } into g 
      select new { 
       g.Key.Name, 
       g.Key.Value, 
       Count = g.Count() 
      }; 

用法:

foreach(var item in query) 
{ 
    // item.Name 
    // item.Value 
    // item.Count 
} 

如果你想要得到的另一個數據表,那麼你可以使用CopyToDataTable擴展在MSDN文章How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow描述:

DataTable result = query.CopyToDataTable(); 
0

這是做這件事:

IEnumerable<IGrouping<Tuple<string,string>, DataRow>> groups= table.Rows.OfType<DataRow>().GroupBy(x=> new Tuple<string,string>(x["Name"].ToString(), x["Value"].ToString())); 

foreach (var group in groups) 
{ 
    //Name Value: Count 
    Console.WriteLine(group.Key.Item1 + " " + group.Key.Item2 + ": " + group.Count()); 
}