有没有一种更简单的方法来初始化一个List< KeyValuePair< T,U>>中像字典< T,U>? [英] Is there a an easier way to initialize a List<KeyValuePair<T, U>>, like a Dictionary<T, U>?

查看:217
本文介绍了有没有一种更简单的方法来初始化一个List< KeyValuePair< T,U>>中像字典< T,U>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其实我需要的东西像名单,其中,KeyValuePair&LT; T,U&GT;&GT; ,但我希望能够将其初始化像字典(即不写新KeyValuePair <​​/ code>每次)。像这样的:

 词典&LT;字符串,字符串&GT; DIC =新字典&LT;字符串,字符串&GT;
{
    {键1,值1},
    {KEY2,值2}
};
 

解决方案

编辑:原来,.NET的确实的有一个组合列表/字典类型已:的 OrderedDictionary 。不幸的是,这是一个非泛型类型,使得它,而在我看来不那么有吸引力。但是,它保留了插入顺序,如果你只需要调用添加反复。

这是一个有点怪的叫添加并的没有的影响,其中一个键已经存在的条目,而使用的索引添加一个键/值对将覆盖previous关联。基本上,它似乎并不像一个非常不错的API,而我个人还是避免它,除非你的用例的完全的匹配它的行为。


没有,.NET没有任何插入命令 - preserving字典。你总是可以编写自己的基于列表的类型有关添加方法。这甚至可能是几个地方我会考虑扩展现有的类型之一:

 公共类KeyValueList&LT; TKEY的,TValue&GT; :列表&LT; KeyValuePair&LT; TKEY的,TValue&GT;&GT;
{
    公共无效添加(TKEY的关键,TValue值)
    {
        加入(新KeyValuePair&LT; TKEY的,TValue&GT;(键,值));
    }
}
 

然后:

  VAR列表=新KeyValueList&LT;字符串,字符串&GT;
{
    {键1,值1},
    {KEY2,值2}
};
 

另一种方法是使用成分,但我的的感觉:的是,这是一个合理的使用继承。我不能把为什么我很高兴在这种情况下,而不是通常情况下,你要知道...

Actually I need something like List<KeyValuePair<T, U>> but I want to be able to initialize it like dictionary (i.e. without writing new KeyValuePair every time). Like this:

Dictionary<string, string> dic = new Dictionary<string, string>
{
    { "key1", "value1"}, 
    { "key2", "value2"}
};

解决方案

EDIT: It turns out .NET does have a combination list/dictionary type already: OrderedDictionary. Unfortunately this is a non-generic type, making it rather less attractive in my view. However, it retains the insertion order if you just call Add repeatedly.

It's a little strange as calling Add does not affect entries where a key already exists, whereas using the indexer to add a key/value pair will overwrite a previous association. Basically it doesn't seem like a terribly nice API, and I would personally still avoid it unless your use case exactly matches its behaviour.


No, .NET doesn't have any insertion-order-preserving dictionaries. You could always write your own list-based type with the relevant Add method. This might even be one of the few places I'd consider extending an existing type:

public class KeyValueList<TKey, TValue> : List<KeyValuePair<TKey, TValue>>
{
    public void Add(TKey key, TValue value)
    {
        Add(new KeyValuePair<TKey, TValue>(key, value));
    }
}

Then:

var list = new KeyValueList<string, string>
{
    { "key1", "value1"}, 
    { "key2", "value2"}
};

An alternative is to use composition, but my gut feeling is that this is a reasonable use of inheritance. I can't place why I'm happy in this case but not usually, mind you...

这篇关于有没有一种更简单的方法来初始化一个List&LT; KeyValuePair&LT; T,U&GT;&gt;中像字典&LT; T,U&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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