Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About System.Linq.Lookup class

Tags:

c#

linq

I came across this class while reading a C# book and have some questions.

  • Why is this added into System.Linq namespace and not into usuall Collections namespace?
  • What the intention behind this class is
  • Why this class is not intended for direct instantiation? This is available through the ToLookup extension only, right?
like image 569
Samuel Kim Avatar asked Oct 13 '08 10:10

Samuel Kim


People also ask

What is lookup Linq?

LINQ ToLookup() Method ToLookup operator in LINQ is an extension method, and it is used to extract a set of key/value pairs from the source. Here, each element in the resultant collection is a generic Lookup object. Lookup object holds the Key and subsequence items that matched with the Key.

What is ILookUp?

ILookUp => Group by key , Enumerable Collection. Single key value refers to enumerable collection where we can iterate through the value collection. IDictionary => Group by distinct key , Single value. Follow this answer to receive notifications.


2 Answers

Purpose of the class: a dictionary where a key can map to multiple values. Think of it as being for grouping rather than one-to-one mapping.

Only through ToLookup decision: Pass. Again, seems like a bad call to me. On the other hand, it means that the result is immutable to the outside world, which is quite nice. It's quite easy to write your own collection which supports this, of course - but it would be have been quite nice to have it in the collections "properly". My guess is that MS didn't have the time/money to go through the pretty rigorous design/test required to make it a first class collections decision.

Namespace decision: Probably related to the above. Having a version in System.Collections.Generic which you couldn't create yourself would have been a bit odd.

like image 80
Jon Skeet Avatar answered Sep 22 '22 16:09

Jon Skeet


As an aside, note that MiscUtil also includes a MiscUtil.Linq.EditableLookup<,> class, that is similar; it implements the regular ILookup<,> interface, but is fully mutable - so you can create it and add your own values.

like image 33
Marc Gravell Avatar answered Sep 19 '22 16:09

Marc Gravell