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>
精彩评论