C# & Linq: Grouping list members according to a list of values

214 views Asked by At

I have a list of object which all expose a property of type IList. Now I want to group this list by the values of that list. So let say for example:

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

As output I would like to have

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

I thought about a convenient LINQ expression to solve this, but it could not find any reference if it is possible at all. Of cause I can to it with loops... but I'am curious if it is possible with LINQ.

Thanks

4

There are 4 answers

0
Dave On

You can try:

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() } )
0
k.m On

Sample for 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
Marcelo Cantos On

Assuming a structure like this:

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"}},
}

You can write the following query comprehension:

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

If you want to map directly to objects, not just their names, do this instead:

from ob in list
from val in ob.Props
group ob by val
0
Frederiek On
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 };