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

本文关键字:列表 成员 Linq | 更新日期: 2023-09-27 18:20:15

我有一个对象列表,所有对象都公开了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是否有可能。

感谢

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

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);

假设这样的结构:

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

您可以尝试:

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() } )
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 };