82 lines
No EOL
2.3 KiB
C#
82 lines
No EOL
2.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using JD.Collections.Interfaces;
|
|
using JD.Kernel.StaticHelpers;
|
|
|
|
namespace JD.Collections
|
|
{
|
|
/// <summary>
|
|
/// Extends system keyedcollection.
|
|
/// </summary>
|
|
public abstract class KeyedList<TKey, TValue> : System.Collections.ObjectModel.KeyedCollection<TKey, TValue>, IKeyedList<TKey, TValue>
|
|
{
|
|
protected KeyedList()
|
|
{ }
|
|
|
|
protected KeyedList(IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold)
|
|
: base(comparer, dictionaryCreationThreshold)
|
|
{ }
|
|
|
|
/// <summary>
|
|
/// Returns the value if found in the collection.
|
|
/// </summary>
|
|
public bool TryGetValue(TKey key, out TValue result)
|
|
{
|
|
IDictionary<TKey, TValue> underlyingDictionary = Dictionary;
|
|
|
|
if (underlyingDictionary != null)
|
|
{
|
|
return underlyingDictionary.TryGetValue(key, out result);
|
|
}
|
|
|
|
IEqualityComparer<TKey> comparer = Comparer;
|
|
foreach (TValue item in this)
|
|
{
|
|
if (comparer.Equals(GetKeyForItem(item), key))
|
|
{
|
|
result = item;
|
|
return true;
|
|
}
|
|
}
|
|
|
|
result = default(TValue);
|
|
return false;
|
|
}
|
|
|
|
public bool ContainsKey(TKey key)
|
|
{
|
|
return Contains(key);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a concrete collection from a converter.
|
|
/// </summary>
|
|
/// <param name="getKeyForItem"></param>
|
|
/// <returns></returns>
|
|
public static KeyedList<TKey, TValue> Create(Converter<TValue, TKey> getKeyForItem)
|
|
{
|
|
return new ConcreteKeyedList(getKeyForItem);
|
|
}
|
|
|
|
#region Nested
|
|
|
|
private class ConcreteKeyedList : KeyedList<TKey, TValue>
|
|
{
|
|
private readonly Converter<TValue, TKey> m_getKeyForItem;
|
|
|
|
public ConcreteKeyedList(Converter<TValue, TKey> getKeyForItem)
|
|
{
|
|
Throw.IfNull(getKeyForItem, "getKeyForItem");
|
|
|
|
m_getKeyForItem = getKeyForItem;
|
|
}
|
|
|
|
protected override TKey GetKeyForItem(TValue item)
|
|
{
|
|
return m_getKeyForItem(item);
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
} |