Empty ILookup<K, T>

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.


You can create a singleton class for empty lookups.

using System.Linq;

public sealed class EmptyLookup<T, K> : ILookup<T, K> 
{
        public static readonly EmptyLookup<T, K> Instance { get; }
            = new EmptyLookup<T, K>();

        private EmptyLookup() { }

        public bool Contains(T key) => false;

        public int Count => 0;

        public IEnumerable<K> this[T key] => Enumerable.Empty<K>();

        public IEnumerator<IGrouping<T, K>> GetEnumerator()
          => Enumerable.Empty<IGrouping<K, V>>().GetEnumerator();

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
 }

then you can write code like this:

var x = EmptyLookup<int, int>.Instance;

The benefit of creating a new class is that you can use the "is" operator and check for type equality:

if (x is EmptyLookup<,>) {
 // ....
}

Tags:

C#

.Net

Ilookup