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
?
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; } } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With