C# 使用成员作为键的.Net字典类型

C# 使用成员作为键的.Net字典类型,c#,generics,dictionary,C#,Generics,Dictionary,我一直在使用自定义类中键入的字典,然后将它们键入外部值。为了更好地封装,我想使用类的一个属性作为键值。有没有一种简单的方法可以做到这一点,而无需创建字典的自定义实现 例如: public class MyStuff{ public int num{get;set;} public string val1{get;set;} public string val2{get;set;} } var dic = new Dictionary<int, MyStuff>

我一直在使用自定义类中键入的字典,然后将它们键入外部值。为了更好地封装,我想使用类的一个属性作为键值。有没有一种简单的方法可以做到这一点,而无需创建字典的自定义实现

例如:

public class MyStuff{
    public int num{get;set;}
    public string val1{get;set;}
    public string val2{get;set;}
}

var dic = new Dictionary<int, MyStuff>();
公共类MyStuff{
公共int num{get;set;}
公共字符串val1{get;set;}
公共字符串val2{get;set;}
}
var dic=新字典();
有类似的选择吗-

var dic = new Dictionary<x=> x.num, MyStuff>(); 
var dic=newdictionary x.num,MyStuff>();
我想你在找

与字典不同,
KeyedCollection
的元素不是键/值对;相反,整个元素是值,键嵌入在值中。例如,从
KeyedCollection
KeyedCollection(String,String的)
)派生的集合元素可能是“John Doe Jr.”,其中值是“John Doe Jr.”,键是“Doe”;或者,可以从
KeyedCollection
派生包含整数键的员工记录集合。抽象
GetKeyForItem
方法从元素中提取键

您可以通过委托轻松创建实现
GetKeyForItem
的派生类:

public class ProjectedKeyCollection<TKey, TItem> : KeyedCollection<TKey, TItem>
{
    private readonly Func<TItem, TKey> keySelector;

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

    protected override TKey GetKeyForItem(TItem item)
    {
        return keySelector(item);
    }
}
公共类ProjectedKeyCollection:KeyedCollection
{
专用只读Func键选择器;
public ProjectedKeyCollection(Func keySelector)
{
this.keySelector=keySelector;
}
受保护的覆盖TKey GetKeyForItem(TItem项目)
{
返回键选择器(项目);
}
}
然后:

var dictionary=newprojectedkeycollection(x=>x.num);

看起来非常危险。。。如果我可以内联指定一个匿名方法来检索密钥,而不是实现接口,那就太好了。nm,我知道这就是您在这里实现的;)
var dictionary = new ProjectedKeyCollection<int, MyStuff>(x => x.num);