HappyNomad
HappyNomad

Reputation: 4548

ToLookup vs. ReadOnlyCollection

I've been using LINQ-to-objects for quite a while, but I just now noticed the Enumerable.ToLookup extension method and read its documentation. I came across it while looking for the quickest way to get a read-only interface to an IEnumerable<T>. It seems to me that appending .ToLookup( o => o ) onto the enumerable results in a System.Linq.Lookup object that can serve the same purpose as a ReadOnlyCollection<T>.

So why would I ever create a direct instance of ReadOnlyCollection<T> again?

Upvotes: 1

Views: 232

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564423

A lookup is not, conceptually, the same as a read-only enumerable. It's more like a dictionary where each key has multiple values, and is used to look up matching values by key. Calling ToLookup enumerates the input fully and builds the lookup.

A ReadOnlyCollection<T> would be far less expensive as it merely wraps any IList<T>, as well as matching the semantic meaning of a read only interface to an IEnumerable<T>.

Upvotes: 3

Related Questions