0xDEADBEEF
0xDEADBEEF

Reputation: 3431

LINQ: Assinging Property-values in IEnumerable<T>

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

Upvotes: 3

Views: 100

Answers (1)

Mark Byers
Mark Byers

Reputation: 837926

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:

Upvotes: 7

Related Questions