我有一个数据表:
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
答案 0 :(得分:0)
此Linq to DataSet查询将分组值作为匿名对象返回
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
}
如果您希望将结果作为另一个DataTable,那么您可以使用CopyToDataTable
扩展,如MSDN文章How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow中所述:
DataTable result = query.CopyToDataTable();
答案 1 :(得分: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());
}