如何在我声明的同一行中初始化C#List.(IEnumerable字符串Collection示例)

Joh*_*nes 98 c# collections initialization list

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

List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");
Run Code Online (Sandbox Code Playgroud)

我很想写

List<string> nameslist = new List<string>({"one", "two", "three"});
Run Code Online (Sandbox Code Playgroud)

但是{"one","two","three"}不是"IEnumerable string Collection".如何使用IEnumerable字符串Collection在一行中初始化它?

Mat*_*ott 156

var list = new List<string> { "One", "Two", "Three" };
Run Code Online (Sandbox Code Playgroud)

本质上语法是:

new List<Type> { Instance1, Instance2, Instance3 };
Run Code Online (Sandbox Code Playgroud)

这是由编译器翻译的

List<string> list = new List<string>();
list.Add("One");
list.Add("Two");
list.Add("Three");
Run Code Online (Sandbox Code Playgroud)

  • 它并没有被完全翻译成,至少在一般情况下并非如此.在完成所有`Add`调用之后,对变量的赋值发生了 - 就好像它使用了一个临时变量,最后是`list = tmp;`.如果您*重新分配*变量的值,这可能很重要. (9认同)

Adr*_*der 16

将代码更改为

List<string> nameslist = new List<string> {"one", "two", "three"};
Run Code Online (Sandbox Code Playgroud)

要么

List<string> nameslist = new List<string>(new[] {"one", "two", "three"});
Run Code Online (Sandbox Code Playgroud)


Man*_*ore 7

为想要使用 POCO 初始化列表的人们发布此答案,因为这是搜索中弹出的第一件事,但所有答案仅适用于字符串类型列表。

您可以通过两种方式执行此操作,一种是通过 setter 赋值直接设置属性,或者通过创建一个接受参数并设置属性的构造函数来更简洁。

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"} };
Run Code Online (Sandbox Code Playgroud)

或者通过参数化构造函数

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")};


        
Run Code Online (Sandbox Code Playgroud)


Ric*_*ett 6

只是丢失括号:

var nameslist = new List<string> { "one", "two", "three" };
Run Code Online (Sandbox Code Playgroud)