C# LookUp helper

Date: 2022-04-07

Mainly because ToDictionary/ToLookup crashes on null / duplicate values + IDictionary TryGetValue is cumbersome

using System;
using System.Collections.Generic;

namespace Domain.Helpers
{
    public interface IDict<Key, T>
    {
        T ByKey(Key key);
    }

    public class LookUpHelper
    {
        public static IDict<Key, T> From<Key, T>(IEnumerable<T> items, Func<T, Key> keySelector) => new LookUp<Key, T>(items, keySelector);

        private class LookUp<Key, T> : IDict<Key, T>
        {
            public LookUp(IEnumerable<T> items, Func<T, Key> keySelector)
            {
                Items = ToDictionarySafe(items, keySelector);
            }
            public LookUp(IDictionary<Key, T> items)
            {
                Items = items;
            }
            private IDictionary<Key, T> Items { get; }
            public T ByKey(Key key)
            {
                if (key == null) return default;
                Items.TryGetValue(key, out var val);
                return val;
            }
            private Dictionary<Key, T> ToDictionarySafe(IEnumerable<T> items, Func<T, Key> keySelector)
            {
                var dict = new Dictionary<Key, T>();
                foreach (var item in items)
                {
                    var key = keySelector(item);
                    if (key == null || dict.ContainsKey(key)) continue;
                    dict[key] = item;
                }
                return dict;
            }
        }
    }
}

61100cookie-checkC# LookUp helper