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

后端 未结 8 859
眼角桃花
眼角桃花 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 15:54
    List<string> nameslist = new List<string> {"one", "two", "three"} ?
    
    0 讨论(0)
  • 2021-01-30 16:02

    Change the code to

    List<string> nameslist = new List<string> {"one", "two", "three"};
    

    or

    List<string> nameslist = new List<string>(new[] {"one", "two", "three"});
    
    0 讨论(0)
  • 2021-01-30 16:02

    Just lose the parenthesis:

    var nameslist = new List<string> { "one", "two", "three" };
    
    0 讨论(0)
  • 2021-01-30 16:02

    Remove the parentheses:

    List<string> nameslist = new List<string> {"one", "two", "three"};
    
    0 讨论(0)
  • 2021-01-30 16:07
    var list = new List<string> { "One", "Two", "Three" };
    

    Essentially the syntax is:

    new List<Type> { Instance1, Instance2, Instance3 };
    

    Which is translated by the compiler as

    List<string> list = new List<string>();
    list.Add("One");
    list.Add("Two");
    list.Add("Three");
    
    0 讨论(0)
  • 2021-01-30 16:08

    It depends which version of C# you're using, from version 3.0 onwards you can use...

    List<string> nameslist = new List<string> { "one", "two", "three" };
    
    0 讨论(0)
提交回复
热议问题