C#& Linq:根据值列表对列表成员进行分组

时间:2012-01-13 10:51:41

标签: c# linq grouping multivalue

我有一个对象列表,它们都公开了IList类型的属性。 现在我想按列表的值对此列表进行分组。所以,举个例子说:

OB1: Property is A, B, C  
OB2: Property is D, C, E  
OB3: Property is B, E, C

作为输出我希望

A: OB1  
B: OB1, OB3  
C: OB1, OB2, OB3  
D: OB2  
E: OB2, OB3

我想到了一个方便的LINQ表达式来解决这个问题,但是如果可能的话,它找不到任何引用。因为我可以用循环来解决这个问题...但是如果LINQ可以实现,我很好奇。

由于

4 个答案:

答案 0 :(得分:1)

LINQPad的示例:

var original = new[]
{
    new { Name = "OB1", Property  = new [] { "A", "B", "C" } },
    new { Name = "OB2", Property  = new [] { "D", "C", "E" } },
    new { Name = "OB3", Property  = new [] { "B", "E", "C" } },
};

var output = original
    .SelectMany(o => o.Property, (o, i) => new { Name = o.Name, Item = i })
    .GroupBy(e => e.Item);

答案 1 :(得分:1)

假设这样的结构:

var list = new [] {
  new {Name="OB1", Prop=new[]{"A", "B", "C"}},
  new {Name="OB2", Prop=new[]{"D", "C", "E"}},
  new {Name="OB3", Prop=new[]{"B", "E", "C"}},
}

您可以编写以下查询理解:

from ob in list
let Name = ob.Name
from val in ob.Props
group ob.Name by val

如果您想直接映射到对象,而不仅仅是他们的名字,请改为:

from ob in list
from val in ob.Props
group ob by val

答案 2 :(得分:0)

您可以尝试:

list
  .SelectMany(x => x.Property.Select(p => new { Key = p, Value = x }))
  .GroupBy(p => p.Key)
  .Select(g => new { g.Key, Values = g.Select(x => x.Value).ToList() } )

答案 3 :(得分:0)

var list = new[] {
              new {Name="OB1", Prop=new[]{"A", "B", "C"}},
              new {Name="OB2", Prop=new[]{"D", "C", "E"}},
              new {Name="OB3", Prop=new[]{"B", "E", "C"}},
            };

var props = from prop in (from item in list
                          from p in item.Prop
                          select p).Distinct()
            let names = list.Where(i => i.Prop.Contains(prop)).Select(i => i.Name).ToArray()
            select new { prop, names };