2

我有一个对象列表,它们都公开了 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

4 回答 4

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);
于 2012-01-13T11:02:34.577 回答
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
于 2012-01-13T11:06:56.727 回答
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() } )
于 2012-01-13T11:02:26.933 回答
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 };
于 2012-01-13T12:07:52.243 回答