Jeśli konsekwentnie chcesz porównać przewidywane klawiszy (takie jak pojedynczy obiekt), można zdefiniować klasę, która zamyka cały klucz porównania logika dla Ciebie, w tym kontrole null, klucz wydobycia z obu obiektów i klucz porównaniu z zastosowaniem określonego czy ustawiona wewnętrzną porównywarka:
public class KeyComparer<TSource, TKey> : Comparer<TSource>
{
private readonly Func<TSource, TKey> _keySelector;
private readonly IComparer<TKey> _innerComparer;
public KeyComparer(
Func<TSource, TKey> keySelector,
IComparer<TKey> innerComparer = null)
{
_keySelector = keySelector;
_innerComparer = innerComparer ?? Comparer<TKey>.Default;
}
public override int Compare(TSource x, TSource y)
{
if (object.ReferenceEquals(x, y))
return 0;
if (x == null)
return -1;
if (y == null)
return 1;
TKey xKey = _keySelector(x);
TKey yKey = _keySelector(y);
return _innerComparer.Compare(xKey, yKey);
}
}
dla wygody, metodę fabryczną:
public static class KeyComparer
{
public static KeyComparer<TSource, TKey> Create<TSource, TKey>(
Func<TSource, TKey> keySelector,
IComparer<TKey> innerComparer = null)
{
return new KeyComparer<TSource, TKey>(keySelector, innerComparer);
}
}
Można wtedy użyć tego tak:
var sortedSet = new SortedSet<MyClass>(KeyComparer.Create((MyClass o) => o.MyProperty));
Można odwołać się do moich blog post do rozszerzonej dyskusji tej realizacji.
Możliwa odpowiedź tutaj: http://stackoverflow.com/questions/9824435/interface-implementing-anonymous-class-in-c –