How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

后端 未结 8 860
眼角桃花
眼角桃花 2021-01-30 15:20

I am writing my testcode and I do not want wo write:

List nameslist = new List();
nameslist.Add(\"one\");
nameslist.Add(\"two\");
nam         


        
相关标签:
8条回答
  • 2021-01-30 16:10

    I think this will work for int, long and string values.

    List<int> list = new List<int>(new int[]{ 2, 3, 7 });
    
    
    var animals = new List<string>() { "bird", "dog" };
    
    0 讨论(0)
  • 2021-01-30 16:18

    This is one way.

    List<int> list = new List<int>{ 1, 2, 3, 4, 5 };
    

    This is another way.

    List<int> list2 = new List<int>();
    
    list2.Add(1);
    
    list2.Add(2);
    

    Same goes with strings.

    Eg:

    List<string> list3 = new List<string> { "Hello", "World" };
    
    0 讨论(0)
提交回复
热议问题