C# Simple Data Collection with dictionary

Date: 2022-01-11
using System;
using System.Collections;
using System.Collections.Generic;

public class DataCollection<TClass, TKey> : IEnumerable<TClass>
{
    private readonly Dictionary<TKey, TClass> itemsByKey;

    public DataCollection(IEnumerable<TClass> items, Func<TClass, TKey> keySelector)
    {
        itemsByKey = ToDictionarySafe(items, keySelector);
    }

    private IEnumerable<TClass> AsEnumerable() => itemsByKey.Values;

    public TClass GetKey(TKey key, TClass def = default(TClass))
    {
        if (itemsByKey.TryGetValue(key, out var val)) return val;
        return def;
    }

    public IEnumerator<TClass> GetEnumerator() => AsEnumerable().GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => AsEnumerable().GetEnumerator();

    public static Dictionary<Y, T> ToDictionarySafe<T, Y>(IEnumerable<T> items, Func<T, Y> keySelector)
    {
        var dict = new Dictionary<Y, T>();
        foreach (var item in items)
        {
            var key = keySelector(item);
            if (key != null && !dict.ContainsKey(key))
            {
                dict[key] = item;
            }
        }
        return dict;
    }
}
59220cookie-checkC# Simple Data Collection with dictionary