Search code examples
c#linqgeneric-collections

C# Linq - Extract members of list within dictionary


I have a use case for a dictionary like this one

var foo = new Dictionary<string, List<string>>()

so this collection will hold some hierarchical data like this

  • Key 1
    • Value 1
    • Value 2
  • Key 2
    • Value 3

and I need to get\project a list of values ignoring the keys, so result would be

  • Value 1
  • Value 2
  • Value 3

on the first attempt I came up with this

IReadOnlyList<string> bar = foo.Select(r => r.Value.Select(x => x.ToString()))
                             .Select(r => r.ToString())
                             .ToList();

Is this any good?


Solution

  • Use SelectMany:

    foo.SelectMany(x => x.Value).ToList();