I have a ILookup<TKey,TElement> lookup from which I fairly often get elements and iterate trough them using LINQ or foreach. I look up like this IEnumerable<TElement> results = lookup[key];.
Thus, results needs to be enumerated at least once every time I use lookup results (and even more if I’m iterating multiple times if I don’t use .ToList() first).
Even though its not as “clean”, wouldn’t it be better (performance-wise) to use a Dictionary<TKey,List<TElement>>, so that all results from a key are only enumerated on construction of the dictionary? Just how taxing is ToList()?
ToLookup, like all the otherToXXXLINQ methods, uses immediate execution. The resulting object has no reference to the original source. It effectively does build aDictionary<TKey, List<TElement>>– not those exact types, perhaps, but equivalent to it.Note that there’s a difference though, which may or may not be useful to you – the indexer for a lookup returns an empty sequence if you give it a key which doesn’t exist, rather than throwing an exception. That can make life much easier if you want to be able to just index it by any key and iterate over the corresponding values.
Also note that although it’s not explicitly documented, the implementation used for the value sequences does implement
ICollection<T>, so calling the LINQCount()method is O(1) – it doesn’t need to iterate over all the elements.See my Edulinq post on
ToLookupfor more details.