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"
}();
11 answers
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
Apenas remova ()
no final.
List<string> optionList = new List<string>
{ "AdditionalCardPersonAdressType", /* rest of elements */ };
List<string> optionList = new List<string> { "string1", "string2", ..., "stringN"};
Isto é, sem seguir () depois da lista.
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
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"
};
É 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.
Mover entre parêntesis assim:
var optionList = new List<string>(){"AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"};
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"
}
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"
};
List<string> animals= new List<string>();
animals.Add("dog");
animals.Add("tiger");
List <string> list1 = new List <string>();
using System.Collections.Generic;