如何在声明时初始化C# List(IEnumerable string集合示例)?

142

我正在编写我的测试代码,但我不想写:

List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");

我很想写作

List<string> nameslist = new List<string>({"one", "two", "three"});

然而 {"one", "two", "three"} 并不是一个“IEnumerable string集合”。我该如何使用“IEnumerable string集合”在一行中初始化它?

10个回答

222
var list = new List<string> { "One", "Two", "Three" };

基本上语法是:

new List<Type> { Instance1, Instance2, Instance3 };

这将由编译器翻译为

List<string> list = new List<string>();
list.Add("One");
list.Add("Two");
list.Add("Three");

1
我喜欢这种无括号的方法,这是从哪个C#版本开始的? - SilverbackNet
10
一般来说,它并不完全翻译成那样。所有的“Add”调用完成后,才会对变量进行赋值 - 就好像使用了一个临时变量,并在最后使用“list = tmp;”。如果您要重新分配变量的值,则这很重要。 - Jon Skeet
自动属性和对象初始化程序是在我认为的.NET 3中引入的,它是相同的框架版本,只是更新了编译器以支持LINQ。 - Matthew Abbott
@Jon,谢谢,我从来不知道那一部分。 :D - Matthew Abbott
@Jon Skeet: "...如果你正在重新分配变量的值,这可能非常重要。" 你能详细解释一下这个评论吗? - Tony
1
@Tony 请考虑:list = new List<string> { list[1], list[2], list[0] }; - 在元素添加之前,您不希望将 list 替换为空的 List<string> - NetMage

22

修改代码为

List<string> nameslist = new List<string> {"one", "two", "three"};
或者
List<string> nameslist = new List<string>(new[] {"one", "two", "three"});

1
使用第二行 "List<string> nameslist = new List<string>(new[] {"one", "two", "three"}); " 的目的是什么?我们什么时候可以使用它?另外,第二个语法中 "new[] {...}" 的意思是什么?为什么要在括号 [] 中使用 new 关键字? - Tony

7

为了帮助那些想要使用 POCOs 初始化列表的人们,我发布了这个答案,也因为这是在搜索中首先显示的内容,但所有答案都只针对字符串类型的列表。

有两种方法可以实现这种操作,一种是通过设置属性的赋值方式直接进行,另一种更简洁的方式是创建一个接收参数并设置属性的构造函数。

class MObject {        
        public int Code { get; set; }
        public string Org { get; set; }
    }

List<MObject> theList = new List<MObject> { new MObject{ PASCode = 111, Org="Oracle" }, new MObject{ PASCode = 444, Org="MS"} };

或通过参数化构造函数

class MObject {
        public MObject(int code, string org)
        {
            Code = code;
            Org = org;
        }

        public int Code { get; set; }
        public string Org { get; set; }
    }

List<MObject> theList = new List<MObject> {new MObject( 111, "Oracle" ), new MObject(222,"SAP")};


        

7

只需要去掉括号:

var nameslist = new List<string> { "one", "two", "three" };

哎呀,看起来有五个人比我先做了。 - Richard Fawcett

4

这是一种方式。

List<int> list = new List<int>{ 1, 2, 3, 4, 5 };

这是另一种方式。

List<int> list2 = new List<int>();

list2.Add(1);

list2.Add(2);

同样适用于字符串。
例如:
List<string> list3 = new List<string> { "Hello", "World" };

3
List<string> nameslist = new List<string> {"one", "two", "three"} ?

3
去除括号:
List<string> nameslist = new List<string> {"one", "two", "three"};

3

这要看您使用的C#版本,从3.0版本开始,您可以使用...

List<string> nameslist = new List<string> { "one", "two", "three" };

3
我认为这对于整数、长整数和字符串值都适用。最初的回答。
List<int> list = new List<int>(new int[]{ 2, 3, 7 });


var animals = new List<string>() { "bird", "dog" };

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接