Dave
Dave

Reputation: 125

Map multiple object properties using LINQ GroupBy

I am trying to map an object to another object, but I want to group by a key. I have managed to create the below query, but I need to populate more properties on the object as well as the key and the values.

      var results = list.GroupBy(
    c => c.PropertyKey,
    c => c.Value,
    (key, v) => new MyObject {PropertyKey = key, Values = v.ToList()}
  );

However, MyObject has another property Color that I would also like to populate from list.

I am trying to do something like:

      var results = list.GroupBy(
    c => c.PropertyKey,
    c => c.Color,
    c => c.Value,
    (key, v) => new MyObject {PropertyKey = key, Color = ???, Values = v.ToList()}
  );

Can anyone recommend a clean way to do this?

Upvotes: 0

Views: 1507

Answers (1)

John Woo
John Woo

Reputation: 263843

you can specify them as anonymous object

.GroupBy(c => new { c.PropertyKey, c.Color }, 
         c => c.Value,
        (key, v) => new MyObject { 
                        PropertyKey = key.PropertyKey, 
                        Color = key.Color, 
                        Values = v.ToList() });

Upvotes: 3

Related Questions