0

How can I get from this:

var props = new List<RoomProperties>();
props.Add(new RoomProperties(new[] {3, 4, 5}, new string[] {"AC", "WC"}));
props.Add(new RoomProperties(new[] {2}, new string[] {"AC", "TV"}));
props.Add(new RoomProperties(new[] {3}, new string[] {"Music", "Phone"}));

To this:

Key = 2, Values = ("AC", "TV") 
Key = 3, Values = ("AC", "WC","Music", "Phone" )
Key = 4, Values = ("AC", "WC") 
Key = 5, Values = ("AC", "WC") 

With props.props.SelectMany() I can get keys to flatten, but values are not associated with it. If you have a good idea how do do this in elegant way I would appreciate that. Basically I want room properties concatenated per ID and IDs are uniquely represented with that data.

private class RoomProperties
{
    public readonly int[] RoomIds;
    public string[] Properties { get; private set; }

    public RoomProperties(int[] roomIds, string[] properties)
    {
        RoomIds = roomIds;
        Properties = properties;
    } 
}
Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
rene98c
  • 21
  • 3

1 Answers1

2

You can flatten sequence to anonymous objects with room id and room properties. Then group these object by room id, and select all properties from group (I also added Distinct to avoid duplicated values for room):

props.SelectMany(p => p.RoomIds.Select(id => new { id, p.Properties }))
     .GroupBy(x => x.id)
     .Select(g => new { 
         g.Key, 
         Values = g.SelectMany(x => x.Properties).Distinct() 
     });
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459