Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign value to a new list using linq

Tags:

c#

linq

Let's say I have a class called Company

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

I have a list called CompanyList

var companyList = new List<Company>();

I would like to assign name = "Company A", id = "001" to this empty companyList variable.

How do I do so?

 companyList.FirstOrDefault().Name = "Company A";
 companyList.FirstOrDefault().Id = "001";
like image 206
superninja Avatar asked Dec 03 '22 18:12

superninja


2 Answers

Before you can assign a value to a company in a collection, you must add a company to the collection. You are setting the values of that company, not of the collection itself.

Use either:

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

Or:

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";
like image 163
Jonathan Wood Avatar answered Dec 06 '22 08:12

Jonathan Wood


You could use collection initializer:

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

effectively the same as bellow, a bit more compact

var companyList = new List<Company>();
companyList.Add(new Company { Name = "Company A", Id = "001" });
like image 36
Johnny Avatar answered Dec 06 '22 06:12

Johnny