Search code examples
c#linqlambdalinq-groupigrouping

C# LINQ GroupBy to convert a List to a group with one property as List of values


I have a list of objects list1

Name Value
N1   V100 
N2   V101
N1   V102
N4   V103
N4   V104

I want to convert this into a grouped List

Name Values
N1   V100, V102 
N2   V101
N4   V103, V104

When I use GroupBy I get the whole thing, ( list1.GroupBy(key => key.Name) )

Name Values
N1
  N1   V100
  N1   V102
N2
  N2   V101
N4
  N4   V103
  N4   V104

I just want the values as a List.


Solution

  • After GroupBy, use ToDictionary:

    source.GroupBy(x => x.Name)
          .ToDictionary(x => x.Key, x => x.Select(e => e.Value).ToList());
    

    This yields a Dictionary<string, List<string>> where the keys are the names and the values are lists made up of projecting each element to a string under that specific group.

    I assume that Value is a string for example purposes only but in reality, it doesn't really matter as the solution remains the same.