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

后端 未结 11 1320
猫巷女王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:09

    Just remove () at the end.

    List<string> optionList = new List<string>
                { "AdditionalCardPersonAdressType", /* rest of elements */ };
    
    0 讨论(0)
  • 2020-11-28 19:09
    List<string> facts = new List<string>() {
            "Coronavirus (COVID-19) is an illness caused by a virus that can spread from personto person.",
            "The virus that causes COVID-19 is a new coronavirus that has spread throughout the world. ",
            "COVID-19 symptoms can range from mild (or no symptoms) to severe illness",
            "Stay home if you are sick,except to get medical care.",
            "Avoid public transportation,ride-sharing, or taxis",
            "If you need medical attention,call ahead"
            };
    
    0 讨论(0)
  • 2020-11-28 19:18

    Your function is just fine but isn't working because you put the () after the last }. If you move the () to the top just next to new List<string>() the error stops.

    Sample below:

    List<string> optionList = new List<string>()
    {
        "AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
    };
    
    0 讨论(0)
  • 2020-11-28 19:20

    This is how you initialize and also you can use List.Add() in case you want to make it more dynamic.

    List<string> optionList = new List<string> {"AdditionalCardPersonAdressType"};
    optionList.Add("AutomaticRaiseCreditLimit");
    optionList.Add("CardDeliveryTimeWeekDay");
    

    In this way, if you are taking values in from IO, you can add it to a dynamically allocated list.

    0 讨论(0)
  • 2020-11-28 19:21

    Move round brackets like this:

    var optionList = new List<string>(){"AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"};
    
    0 讨论(0)
提交回复
热议问题