Answers:
查看C#3.0的Collection初始化器。
var list = new List<string> { "test1", "test2", "test3" };
如果您想减少混乱,请考虑
var lst = new List<string> { "foo", "bar" };
这使用了C#3.0的两个功能:类型推断(var
关键字)和列表的集合初始值设定项。
或者,如果您可以使用数组,则它甚至会更短(少量):
var arr = new [] { "foo", "bar" };
你可以这样做
var list = new List<string>{ "foo", "bar" };
这是其他常见数据结构的其他一些常见实例:
字典
var dictionary = new Dictionary<string, string>
{
{ "texas", "TX" },
{ "utah", "UT" },
{ "florida", "FL" }
};
数组列表
var array = new string[] { "foo", "bar" };
队列
var queque = new Queue<int>(new[] { 1, 2, 3 });
叠放
var queque = new Stack<int>(new[] { 1, 2, 3 });
如您所见,在大多数情况下,它只是在花括号中添加值,或者实例化一个新数组,后跟花括号和值。
您可以创建帮助程序的通用静态方法来创建列表:
internal static class List
{
public static List<T> Of<T>(params T[] args)
{
return new List<T>(args);
}
}
然后用法非常紧凑:
List.Of("test1", "test2", "test3")
如果要创建带有值的类型列表,请使用以下语法。
假设某类学生喜欢
public class Student {
public int StudentID { get; set; }
public string StudentName { get; set; }
}
您可以列出如下列表:
IList<Student> studentList = new List<Student>() {
new Student(){ StudentID=1, StudentName="Bill"},
new Student(){ StudentID=2, StudentName="Steve"},
new Student(){ StudentID=3, StudentName="Ram"},
new Student(){ StudentID=1, StudentName="Moin"}
};