Empty ILookup<K, T>

Viewed 10906

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?

8 Answers

Based on LukeH answer, I'd create a static class Lookup with an Empty<TKey, TElement> method. In this way you could use is just the same way as Enumerable.Empty<T>.

public static class Lookup
{
    public static ILookup<TKey, TElement> Empty<TKey, TElement>()
        => Enumerable.Empty<TElement>().ToLookup(x => default(TKey));
}

Example Usage: Lookup.Empty<string, string>()

Thanks @mqp for the good idea. I can propose several extension methods based on that approach:

public static class IEnumerableExtensions
{
    public static ILookup<TKey, TElement> ToEmptyLookup<TKey, TElement>(this IEnumerable<TElement> elements) => new TElement[0].ToLookup(k => default(TKey));
    public static ILookup<TKey, TElement> ToEmptyLookup<TKey, TElement>(this IDictionary<TKey, TElement> elements) => new TElement[0].ToLookup(k => default(TKey));
    public static ILookup<TKey, TElement> ToEmptyLookup<TKey, TElement>(this IGrouping<TKey, TElement> elements) => new TElement[0].ToLookup(k => default(TKey));
    public static ILookup<TKey, TElement> ToEmptyLookup<TKey, TElement>(this IEnumerable<ILookup<TKey, TElement>> elements) => new TElement[0].ToLookup(k => default(TKey));
}
Related