如何从列表列表中进行LINQ选择,分组依据和计数?

时间:2018-08-31 14:34:03

标签: c# linq lambda

我有一个List<IEnumerable<Foo>>

这将产生如下列表:

{
    [
      {a: 1, b: 2},
      {a: 1, b: 3}
    ],
    [{a: 1, b: 2}]
}

我需要以这种方式进行排列,将对象按a和b值分组。我无法对以下示例进行组查询。

{
   {a: 1, b: 2, count: 2},
   {a: 1, b: 3, count: 1}
} 

编辑: 这是我拥有的代码和输出:

var list = new List<object>();
foreach (var f in fooList)
{
    var x = from y in f
            group y by new { y.a, y.b } into z
            select new
            {
                Foo = z.Key,
                Count = z.Count()
            };
    a.Add(x);
}

输出:

[
  {
     "Foo": {
         "a": 1,
         "b": 2
     },
     "count": 1
  },
  {
     "Foo": {
         "a": 1,
         "b": 2
     },
     "count": 1
  },
  {
     "Foo": {
         "a": 1,
         "b": 3
     },
     "count": 1
  }
],

2 个答案:

答案 0 :(得分:1)

类似的事情会起作用:

var list = new List<List<Foo>>();
list.Add(new List<Foo> {new Foo {A = 1, B = 2}, new Foo {A = 1, B = 3}});
list.Add(new List<Foo> {new Foo {A = 1, B = 2}});

var result = list.SelectMany(l => l)
    .GroupBy(l => new {l.A, l.B})
    .Select(grp => new {A = grp.Key.A, B = grp.Key.B, Count = grp.Count()});

首先,列表用SelectMany()弄平。之后,我们通过使用匿名对象GroupBy来多个值。分组后,我们将选择初始值和从分组中计数出来的匿名对象。


似乎您希望将结果序列化。使用Json.Net,这将是输出:

[
   {
      "A":1,
      "B":2,
      "Count":2
   },
   {
      "A":1,
      "B":3,
      "Count":1
   }
]

答案 1 :(得分:0)

由于嵌套级别与所需结果无关,因此您必须展平第一个列表。这显示了如何展平。我认为您的GroupBy是正确的。

    List<List<Foo>> list = new List<List<Foo>>();
    list.Add(new List<Foo>());
    list[0].Add(new Foo { a = 1, b = 2 });
    list[0].Add(new Foo { a = 1, b = 3 });
    var subList = new List<Foo>();
    subList.Add(new Foo { a = 1, b = 2 });
    list.Add(subList);
    var flat = list.SelectMany(i => i);
    var grouped = from foo in flat group foo by new { foo.a, foo.b } into g select g;
    Assert.AreEqual(true, grouped.First().Count() == 2);
    Assert.AreEqual(true, grouped.Last().Count() == 1);