How to initialize a list of strings (List) with many string values

后端 未结 11 1239
猫巷女王i
猫巷女王i 2020-11-28 18:40

How is it possible to initialize (with a C# initializer) a list of strings? I have tried with the example below but it\'s not working.

List opt         


        
相关标签:
11条回答
  • 2020-11-28 19:00
    List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
    
    0 讨论(0)
  • 2020-11-28 19:01

    You haven't really asked a question, but the code should be

    List<string> optionList = new List<string> { "string1", "string2", ..., "stringN"}; 
    

    i.e. no trailing () after the list.

    0 讨论(0)
  • 2020-11-28 19:03
    List<string> animals= new List<string>();
    animals.Add("dog");
    animals.Add("tiger");
    
    0 讨论(0)
  • 2020-11-28 19:04

    One really cool feature is that list initializer works just fine with custom classes too: you have just to implement the IEnumerable interface and have a method called Add.

    So for example if you have a custom class like this:

    class MyCustomCollection : System.Collections.IEnumerable
    {
        List<string> _items = new List<string>();
    
        public void Add(string item)
        {
            _items.Add(item);
        }
    
        public IEnumerator GetEnumerator()
        {
            return _items.GetEnumerator();
        }
    }
    

    this will work:

    var myTestCollection = new MyCustomCollection()
    {
        "item1",
        "item2"
    }
    
    0 讨论(0)
  • 2020-11-28 19:04

    This is how you would do it.

    List <string> list1 = new List <string>();

    Do Not Forget to add

    using System.Collections.Generic;

    0 讨论(0)
  • 2020-11-28 19:05
    var animals = new List<string> { "bird", "dog" };
    List<string> animals= new List<string> { "bird", "dog" };
    

    Above two are the shortest ways, please see https://www.dotnetperls.com/list

    0 讨论(0)
提交回复
热议问题