Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty ILookup<K, T>

Tags:

c#

.net

ilookup

I have a method that returns an ILookup. In some cases I want to return an empty ILookup as an early exit. What is the best way of constructing an empty ILookup?

like image 926
Mike Q Avatar asked Jul 25 '11 19:07

Mike Q


2 Answers

Further to the answers from mquander and Vasile Bujac, you could create a nice, straightforward singleton-esque EmptyLookup<K,E> class as follows. (In my opinion, there doesn't seem much benefit to creating a full ILookup<K,E> implementation as per Vasile's answer.)

var empty = EmptyLookup<int, string>.Instance;  // ...  public static class EmptyLookup<TKey, TElement> {     private static readonly ILookup<TKey, TElement> _instance         = Enumerable.Empty<TElement>().ToLookup(x => default(TKey));      public static ILookup<TKey, TElement> Instance     {         get { return _instance; }     } } 
like image 124
LukeH Avatar answered Sep 19 '22 21:09

LukeH


There's no built-in, so I'd just write an extension method that runs something along the lines of new T[0].ToLookup<K, T>(x => default(K));

I strongly doubt returning null would be more correct here. It's almost never the case that you want to return null from a method which returns a collection (as opposed to an empty collection.) I could not possibly disagree more with people who are suggesting that.

like image 32
mqp Avatar answered Sep 18 '22 21:09

mqp