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

Bra*_*itz 2 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>();
Run Code Online (Sandbox Code Playgroud)

有没有类似的选项?——

var dic = new Dictionary<x=> x.num, MyStuff>(); 
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

你正在寻找KeyedCollection<TKey, TItem>

与字典不同, 的元素KeyedCollection<TKey, TItem>不是键/值对;相反,整个元素就是值,而键嵌入在值中。例如,从KeyedCollection<String,String>KeyedCollection(Of String, String)在 Visual Basic 中)派生的集合元素可能是“John Doe Jr”。其中值为“John Doe Jr.”。关键是“Doe”;或包含整数键的员工记录集合可以从KeyedCollection<int,Employee>. 抽象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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

var dictionary = new ProjectedKeyCollection<int, MyStuff>(x => x.num);
Run Code Online (Sandbox Code Playgroud)