使用linq将值分配给新列表

时间:2019-04-04 21:28:40

标签: c# linq

假设我有一个名为Company的班级

public class Company 
{
   public string name;
   public string id;
}

我有一个名为CompanyList的列表

var companyList = new List<Company>();

我想为这个空的companyList变量分配名称=“ Company A”,id =“ 001”。

我该怎么做?

 companyList.FirstOrDefault().Name = "Company A";
 companyList.FirstOrDefault().Id = "001";

5 个答案:

答案 0 :(得分:5)

在为集合中的公司分配值之前,必须将公司添加到集合中。您正在设置该公司的价值,而不是集合本身的价值。

使用以下任一方法:

var companyList = new List<Company>();
companyList.Add(new Company { Name = "Company A", Id = "001" });

或者:

var companyList = new List<Company>();
companyList.Add(new Company());
// Assumes you want to modify the first company in the list
companyList[0].Name = "Company A";
companyList[0].Id = "001";

答案 1 :(得分:5)

以下是您可以直接初始化集合的示例:

var companyList = new List<Company> {
    new Company { name = "Company A", id = "001" },
    new Company { name = "Company B", id = "002" }
};

答案 2 :(得分:4)

您可以使用集合初始化程序

var companyList = new List<Company>{ new Company { Name = "Company A", Id = "001" } };

实际上与波纹管相同,但更紧凑

var companyList = new List<Company>();
companyList.Add(new Company { Name = "Company A", Id = "001" });

答案 3 :(得分:3)

似乎您只需要创建Company的实例,然后将其添加到列表中即可。这是一个示例:

List<Company> companyList = new List<Company>();
Company currentCompany = new Company(){id="001", Name="Company A"};
companyList.Add(currentCompany);

旁注**请注意使用问题中指出的代码段

 companyList.FirstOrDefault().Name = "Company A";
 companyList.FirstOrDefault().Id = "001";

这可能导致未捕获的空引用异常,从而使程序崩溃。使用FirstOrDefault()实例化对象时,请始终检查null。

Company temp = companyList.FirstOrDefault();
if(temp !=null)
{
    temp.Name = "Company A";
    temp.id = "001"; 
}

答案 4 :(得分:0)

要安全地更新列表(不执行),您应该这样做:

 var company =  companyList.FirstOrDefault() ; 
    if (company != null) {
    company.Name ="aaa";
    company.Id = "123" ;
     }