简体   繁体   English

如何使用linq c#或内部通用方法将值分配给任何一个或两个prop?

[英]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 listofCompany已经填满,并且有一些数据。我想使用linq替换其idName

I can able to do it using foreach like below 我可以使用如下的foreach做到这一点

 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 - 但是有没有更好的方法可以不用foreach呢,因为我的foreach代码在其他方法里面,这是一个通用方法,如下所示-

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

Assuming you're alright with generating new Company objects then you can use Select along with ToList . 假设您可以生成新的Company对象,那么可以将SelectToList一起使用。

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 ? 另一方面,为什么NameAddress表示为int seems strange as usually it's represented as a string . 看起来很奇怪,因为通常用string表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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