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

后端 未结 3 795
遥遥无期
遥遥无期 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:56

    Because you do not have a dictionary you cannot use a dictionary initiailzer. You have a list so you could use a list initializer which will be the closest you could get:

    var l = new List> 
    {
        new KeyValuePair("key1", "value1"),
        new KeyValuePair("key2", "value2"),
    };
    

    Here's the minimum requirement for you to use dictionary initializer: the class must implement IEnumerable and the class must have a public method Add which takes 2 arguments (where the first argument represents the key and the second argument the value). So you could write a custom class which satisfies those requirements and you will be able to use the syntax you have shown in your question.

提交回复
热议问题