Is there a an easier way to initialize a List>, like a Dictionary?

后端 未结 3 798
遥遥无期
遥遥无期 2021-01-18 08:35

Actually I need something like List> but I want to be able to initialize it like dictionary (i.e. without writing new KeyVa

3条回答
  •  感情败类
    2021-01-18 08:46

    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 : List>
    {
        public void Add(TKey key, TValue value)
        {
            Add(new KeyValuePair(key, value));
        }
    }
    

    Then:

    var list = new KeyValueList
    {
        { "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...

提交回复
热议问题