2013-03-04 119 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()); 
}