是否有一个类似字典的集合,可以使用其值的属性作为关键? [英] Is there a dictionary like collection that can use a property of its value as the key?

查看:365
本文介绍了是否有一个类似字典的集合,可以使用其值的属性作为关键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

而不是使用 Dictionary< 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< TKey,TValue>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆