是否有一个像集合,可以使用其值的属性作为键的字典? [英] Is there a dictionary like collection that can use a property of its value as the key?
本文介绍了是否有一个像集合,可以使用其值的属性作为键的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
而不是使用词典< 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);
}
}
这篇关于是否有一个像集合,可以使用其值的属性作为键的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文