Como inicializar uma lista de strings (lista) com muitos valores de string

Como é possível inicializar (com um inicializador C#) uma lista de strings? Eu tentei com o exemplo abaixo, mas não está funcionando.

List<string> optionList = new List<string>
{
    "AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
}();
 395
Author: Erik Humphrey, 2010-06-29

11 answers

List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
 493
Author: Zenzer, 2019-09-30 08:52:05

Apenas remova () no final.

List<string> optionList = new List<string>
            { "AdditionalCardPersonAdressType", /* rest of elements */ };
 602
Author: Padel, 2010-06-29 08:50:43
Ainda não fez uma pergunta, mas o código deve ser
List<string> optionList = new List<string> { "string1", "string2", ..., "stringN"}; 

Isto é, sem seguir () depois da lista.

 158
Author: Unsliced, 2010-06-29 08:52:52
var animals = new List<string> { "bird", "dog" };
List<string> animals= new List<string> { "bird", "dog" };

Acima de dois estão os caminhos mais curtos, por favor Veja https://www.dotnetperls.com/list

 33
Author: Sujoy, 2019-05-11 17:25:49

A tua função está óptima, mas não está a funcionar porque colocaste o () depois do último }. Se mover o () para o topo ao lado de new List<string>(), o erro pára.

Amostra abaixo:

List<string> optionList = new List<string>()
{
    "AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
};
 16
Author: Marcello Mello, 2016-06-17 14:10:00

É assim que inicializa e também pode usar a lista.Adicione () no caso de você querer torná-lo mais dinâmico.

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

Desta forma, se estiver a receber valores de IO, pode adicioná-los a uma lista dinamicamente atribuída.

 7
Author: Enye Aaron Shi, 2018-02-02 20:50:20

Mover entre parêntesis assim:

var optionList = new List<string>(){"AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"};
 3
Author: Andrew Kozlov, 2018-10-17 12:52:16

Uma característica muito fixe é que o inicializador de listas funciona muito bem com classes personalizadas também: você tem apenas de implementar a interface IEnumerable e tem um método chamado Add .

Então, por exemplo, se você tem uma classe personalizada como esta:

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();
    }
}
Isto vai funcionar.
var myTestCollection = new MyCustomCollection()
{
    "item1",
    "item2"
}
 1
Author: adospace, 2020-03-03 18:45:18
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"
        };
 1
Author: Frank Odoom, 2020-10-25 05:59:55
List<string> animals= new List<string>();
animals.Add("dog");
animals.Add("tiger");
 -1
Author: raj, 2019-04-02 08:21:48
É assim que o farias.

List <string> list1 = new List <string>();
Não se esqueça de adicionar

using System.Collections.Generic;
 -8
Author: Muhammad Ali, 2017-07-14 06:11:26