其实我需要的东西像名单,其中,KeyValuePair< T,U>>
,但我希望能够将其初始化像字典(即不写新KeyValuePair 每次)。像这样的:
词典<字符串,字符串> DIC =新字典<字符串,字符串>
{
{键1,值1},
{KEY2,值2}
};
解决方案
编辑:原来,.NET的确实的有一个组合列表/字典类型已:的 OrderedDictionary
。不幸的是,这是一个非泛型类型,使得它,而在我看来不那么有吸引力。但是,它保留了插入顺序,如果你只需要调用添加
反复。
这是一个有点怪的叫添加
并的没有的影响,其中一个键已经存在的条目,而使用的索引添加一个键/值对将覆盖previous关联。基本上,它似乎并不像一个非常不错的API,而我个人还是避免它,除非你的用例的完全的匹配它的行为。
没有,.NET没有任何插入命令 - preserving字典。你总是可以编写自己的基于列表的类型有关添加
方法。这甚至可能是几个地方我会考虑扩展现有的类型之一:
公共类KeyValueList< TKEY的,TValue> :列表< KeyValuePair< TKEY的,TValue>>
{
公共无效添加(TKEY的关键,TValue值)
{
加入(新KeyValuePair< TKEY的,TValue>(键,值));
}
}
然后:
VAR列表=新KeyValueList<字符串,字符串>
{
{键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...