是否有一个像集合,可以使用其值的属性作为键的字典?可以使用、字典、有一个、属性

2023-09-03 07:16:30 作者:浮生碾破

而不是使用词典< TKEY的,TValue> 我要某种类型的集合类,可以使用这个值的属性是关键,是有这样的事情?

Instead of using Dictionary<TKey,TValue> I want some type of collection class that can use a property of the value as the key, is there something like this?

推荐答案

是的,有 - 的 System.Collections.ObjectModel.KeyedCollection&LT; TKEY的,TValue&GT;

Yes, there is - System.Collections.ObjectModel.KeyedCollection<TKey, TValue>.

这是抽象的,有没有具体的派生类的框架,据我所看到的,但所有你需要实现的 GetKeyForItem 据我所见。例如,您可以用委托做到这一点:

That's abstract, and there are no concrete derived classes in the framework as far as I can see, but all you need to implement is GetKeyForItem as far as I can see. For example, you could do this with a delegate:

public class DelegatingKeyedCollection<TKey, TItem> : System.Collections.ObjectModel.KeyedCollection<TKey, TItem>
{
    private readonly Func<TItem, TKey> keySelector;

    public DelegatingKeyedCollection(Func<TItem, TKey> keySelector)
    {
        this.keySelector = keySelector;
    }

    protected override TKey GetKeyForItem(TItem item)
    {
        return keySelector(item);
    }
}