Reputation: 243
Let's say that we have a dictionary like this
Dictionary<key, List<obj>>
I want to get all values as list like this
List<obj>
e.g. There are 3 keys in dictionary, key1, key2, key3.
2 values for key1
3 values for key2
5 values for key3
result should be one list that has 10 values!
I think it may be done with foreach and ToList(). I hope simpler and more efficient solution.
Upvotes: 2
Views: 107
Reputation: 3835
Use LINQ SelectMany method:
var list = dictionary.SelectMany(item => item.Value).ToList();
From the docs:
Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.
All you have to do is to specify the selector - the IEnumerable you want to select for each KeyValuePair, which is obviously the value.
Upvotes: 2
Reputation: 236188
You can use Values
property to get all values from dictionary. And SelectMany
linq extension to flatten sequence of lists into sequence of objects:
dictionary.Values.SelectMany(v => v).ToList()
Upvotes: 3