如何创建硬编码列表

本文关键字:编码 列表 创建 何创建 | 更新日期: 2023-09-27 18:07:23

可能重复:
简化采集初始化

我有字符串值,我只想在列表中设置它们。类似

List<string> tempList = List<string>();
tempList.Insert(0,"Name",1,"DOB",2,"Address");

我想我的大脑冻结了:(

如何创建硬编码列表

var tempList = new List<string> { "Name", "DOB", "Address" };

使用集合初始值设定项语法,您甚至不需要显式调用Add()Insert()。编译器会帮你把它们放在那里。

上述声明实际上被编译为:

List<string> tempList = new List<string>();
tempList.Add("Name");
tempList.Add("DOB");
tempList.Add("Address");

您可以用以下数据初始化列表:

var list = new List<string> { "foo", "bar", "baz" };

如果列表已经存在,您也可以使用AddRange来完成同样的事情:

List<string> tempList = new List<string>();
tempList.AddRange( new string[] {"Name", "DOB", "Address"} );