LINQ GroupBy - 如何分组?

时间:2015-09-22 18:32:35

标签: c# linq

我有这段代码:

List<string[]> list = new List<string[]>();
list.Add(new string[] { "A", "q", "t" });
list.Add(new string[] { "B", "w", "t" });
list.Add(new string[] { "B", "e", "r" });
list.Add(new string[] { "A", "r", "t" });
list.Add(new string[] { "B", "t", "e" });

var result = from item in list 
    group item by item[0] into g
    let count = g.Count()
    orderby count descending
    select new { Value = g.Key, Count = count};

foreach (var res in result)
{
    Console.WriteLine("Value: " + res.Value + " Count: " + res.Count);
}

该产品的结果如下:

Value: B Count: 3
Value: A Count: 2

如果没有太多的foreach,我怎样才能得到这个结果?

Values: A q t - Count 2  
Values: A r t - Count 2  
Values: B w t - Count 3  
Values: B e r - Count 3  
Values: B t e - Count 3 

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作

var result = list.GroupBy(innerArray => innerArray[0])
    .SelectMany(
        grp => grp.Select(innerArray  => new
            {
                Values = innerArray, 
                Count = grp.Count()
             }));

foreach(var r in results)
{
    Console.WriteLine("Values: {0} - Count {1}", string.Join(" ", r.Values), r.Count);
}

然后,每个数组的第一个项的第一个分组使用SelectMany将每个组展平回原始数组并包含计数。

这会产生与您的请求完全相同的顺序,这可能与您的数据重合。如果你想确保它按计数升序,你可以在那里抛出OrderBy(g=>g.Count())

答案 1 :(得分:1)

诀窍是使用SelectMany

    var result =  list.GroupBy(x=> x[0])
                      .SelectMany(x=> x, 
                                  (x,xx)=> new {
                                                   Value=string.Join(" ",xx),  
                                                   Count = x.Count()
                                                });