Quick way to create a list of values in C#?

后端 未结 10 2123
梦如初夏
梦如初夏 2021-01-31 13:14

I\'m looking for a quick way to create a list of values in C#. In Java I frequently use the snippet below:

List l = Arrays.asList(\"test1\",\"test2         


        
10条回答
  •  无人及你
    2021-01-31 13:38

    You can do that with

    var list = new List{ "foo", "bar" };
    

    Here are some other common instantiations of other common Data Structures:

    Dictionary

    var dictionary = new Dictionary 
    {
        { "texas",   "TX" },
        { "utah",    "UT" },
        { "florida", "FL" }
    };
    

    Array list

    var array = new string[] { "foo", "bar" };
    

    Queue

    var queque = new Queue(new[] { 1, 2, 3 });
    

    Stack

    var queque = new Stack(new[] { 1, 2, 3 });
    

    As you can see for the majority of cases it is merely adding the values in curly braces, or instantiating a new array followed by curly braces and values.

提交回复
热议问题