所存储的数据的一个属性词典键控 [英] Dictionary keyed on a property of the stored data
本文介绍了所存储的数据的一个属性词典键控的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是创建一个将在数据对象的属性键入一本字典的最简单的方法?例如。想象我有:
What is the easiest way to create a dictionary that will be keyed on a property of the data object? E.g. imagine I have:
interface A
{
string Key{get;}
//other stuff
}
到目前为止,我有:
So far I have:
IDictionary<string, A> dict = new Dictionary<string, A>();
void Add(A a)
{
dict[a.Key] = a; //I would prefer that the collection class managed this relationship
}
A Get(string key)
{
return dict[key];
}
有没有一种更好的方式来达到同样的? (集合并不需要实现的IDictionary,只要它具有所需的索引)。
Is there a nicer way to achieve the same? (the collection doesn't need to implement IDictionary, as long as it has the required indexer).
推荐答案
您可以使用的 KeyedCollection
:
You can use KeyedCollection
:
public class MyCollection : KeyedCollection<string, A>
{
protected override GetKeyForItem(A a)
{
return a.Key;
}
}
这篇关于所存储的数据的一个属性词典键控的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文