-3

我有一个数据表:

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
4

2 回答 2

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,那么您可以使用MSDN 文章How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRowCopyToDataTable中描述的扩展:

DataTable result = query.CopyToDataTable();
于 2013-03-04T22:24:45.120 回答
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());
}
于 2013-03-04T22:24:58.390 回答