开发者

LINQ: Assinging Property-values in IEnumerable<T>

开发者 https://www.devze.com 2023-04-10 17:32 出处:网络
开发者_如何学GoWhat is the LINQ-version of the following code-snippet: List<Car> myCarList = ...;
开发者_如何学Go

What is the LINQ-version of the following code-snippet:

List<Car> myCarList = ...;
foreach(Car c in myCarList)
{
if(c.Name.Equals("VW Passat"))
{
c.Color = Colors.Silver;
}
}

i tried Select like this and it works:

myCarList = myCarList.Where(c=>c.Name.Equals("VW Passat")).Select(c=> new Car(){Color=Colors.Silver, Name=c.Name}).ToList();

But it´s annoying recreating the object, especially if you have many properties to pass. how to do it simpler?

thanks


I might write it like this:

foreach (Car c in myCarList.Where(c => c.Name == "VW Passat"))
{
    c.Color = Colors.Silver;
}

Here the LINQ query is used perform the filtering, but on ordinary loop performs the update. You could write an Enumerable.ForEach or convert to a list and use List<T>.ForEach. But consider that Enumerable.ForEach was omitted deliberately because that's not how LINQ was intended to be used. See here for more details:

  • LINQ equivalent of foreach for IEnumerable<T>
0

精彩评论

暂无评论...
验证码 换一张
取 消