简体   繁体   English

如何初始化字符串列表(List<string> ) 有很多字符串值

[英]How to initialize a list of strings (List<string>) with many string values

How is it possible to initialize (with a C# initializer) a list of strings?如何初始化(使用 C# 初始化程序)字符串列表? I have tried with the example below but it's not working.我已经尝试过下面的示例,但它不起作用。

List<string> optionList = new List<string>
{
    "AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
}();

Just remove () at the end.只需在最后删除()

List<string> optionList = new List<string>
            { "AdditionalCardPersonAdressType", /* rest of elements */ };
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });

You haven't really asked a question, but the code should be你还没有真正提出问题,但代码应该是

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

ie no trailing () after the list.即列表后没有尾随 ()。

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以上两种是最短的方式,请看https://www.dotnetperls.com/list

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.如果将()移动到new List<string>()旁边的顶部,错误就会停止。

Sample below:示例如下:

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

This is how you initialize and also you can use List.Add() in case you want to make it more dynamic.这是您初始化的方式,如果您想让它更加动态,您也可以使用 List.Add()。

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.这样,如果您从 IO 中获取值,您可以将其添加到动态分配的列表中。

像这样移动圆括号:

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

How is it possible to initialize (with a C# initializer) a list of strings?如何使用C#初始化程序初始化字符串列表? I have tried with the example below but it's not working.我已经尝试过下面的示例,但是它不起作用。

List<string> optionList = new List<string>
{
    "AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
}();

There is something else that you might be missing that hasn't been mentioned.还有一些你可能遗漏的东西没有提到。 I think it might be the problem you are having as I suspect you already tried removing the trailing () and still got an error.我认为这可能是您遇到的问题,因为我怀疑您已经尝试删除尾随 () 但仍然出现错误。

First, like others have mentioned here, in your example you do need to remove the trailing ();首先,就像其他人在这里提到的那样,在您的示例中,您确实需要删除尾随 ();

But, also, note that List<> is in the System.Collections.Generic namespace.但是,还要注意 List<> 在 System.Collections.Generic 命名空间中。

So, you need to do one of the following two options: [#1 below is probably the more preferred option]因此,您需要执行以下两个选项之一:[下面的#1 可能是更优选的选项]

(1) Include the use of the namespace at the top of your code with: using System.Collections.Generic; (1) 在代码顶部包含命名空间的使用: using System.Collections.Generic;

or要么

(2) Put the fully qualified path to List in your declaration. (2) 将 List 的完全限定路径放在您的声明中。

System.Collections.Generic.List optList=new System.Collections.Generic.List { "AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay" }; System.Collections.Generic.List optList=new System.Collections.Generic.List { "AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay" };

Hope that helps.希望有帮助。

The error message you receive when you implement List correctly but don't include the System.Collections.Generic namespace is misleading and not helpful:当您正确实现 List 但不包含 System.Collections.Generic 命名空间时收到的错误消息具有误导性且没有帮助:

"Compiler Error CS0308: The non-generic type List cannot be used with type arguments." “编译器错误 CS0308:非泛型类型 List 不能与类型参数一起使用。”

PS - It gives this unhelpful error because if you don't specify that you intend to use System.Collections.Generic.List the compiler assumes you are trying to use System.Windows.Documents.List. PS - 它给出了这个无用的错误,因为如果你没有指定你打算使用 System.Collections.Generic.List 编译器假定你正在尝试使用 System.Windows.Documents.List。

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 .一个非常酷的特性是列表初始值设定项也适用于自定义类:您只需实现IEnumerable接口并拥有一个名为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"
}

我已经看到了内容标签 C#,但如果有人可以使用 Java(这里的搜索词相同):

List<String> mylist = Arrays.asList(new String[] {"element1", "element2", "element3" }.clone());

The right way to initialize along with declaration is :初始化和声明的正确方法是:

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

If you are using C# 9.0 and up you can use the new feature target-typed new expressions Link如果您使用的是 C# 9.0 及更高版本,则可以使用新功能target-typed new expressions 链接

Example:例子:

List<string> stringList = new(){"item1","item2", "item3"} ;

How is it possible to initialize (with a C# initializer) a list of strings?如何使用C#初始化程序初始化字符串列表? I have tried with the example below but it's not working.我已经尝试过下面的示例,但是它不起作用。

List<string> optionList = new List<string>
{
    "AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
}();

This is how you would do it.这就是你要做的。

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

Do Not Forget to add不要忘记添加

 using System.Collections.Generic;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM