简体   繁体   中英

How to assign values to any one or two prop using linq c# or inside generic method?

public class Company
{
    public int id { get; set; }
    public int Name { get; set; }
    public int Address{ get; set; }

}

List<Company> listofCompany = new List<Company>();

listofCompany is already filled and having some data.I want to replace its id and Name using linq

I can able to do it using foreach like below

 foreach (var item in listofCompany )
                        {
                            item.id= 123;
                            item.Name= 999;
                        }

But is there any better way to do it without foreach because my foreach code is there inside other method which is a generic method like below -

MyData<T>(List<T> anylist){}

Assuming you're alright with generating new Company objects then you can use Select along with ToList .

listofCompany.Select(x => new Company 
               {  Id = 123, 
                  Name = 999, 
                  Address = x.Address
               }).ToList();

Otherwise, if you want to modify the objects in place then you're better off with your current approach.

On another note, why is Name and Address represented as int ? seems strange as usually it's represented as a string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM