Concat lists from dictionary-values to IEnumerable

Viewed 114

I have a Dictionary<int, list<T>> and want to get an IEnumerable<T>, that allows me to iterate over all elements of all lists in the dict. This should of course avoid coping all elements and other performance costly operations.

My approach with Linq, that is not quite right:

IEnumerable<T> enumerable = dict.SelectMany(list).Foreach(list.ConcatAll()).ToEnum();

If Linq is not the optimal way, please suggest other options.

1 Answers

Try to use the following code

var enumerable = dict.Values.SelectMany(v => v);

You are accessing the Values collection of dictionary and then use SelectMany method to project every value as List<T> and flatten to the resulting enumeration

Your code doesn't work because SelectMany() accepts Func as collection selector, there is also no need to use Foreach method. ToEnum() method usage isn't a valid here as well, it belongs to Enum type and almost all System.Linq methods already accept or return IEnumerable<T>

Related