3

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

0xDEADBEEF
  • 3,401
  • 8
  • 37
  • 66

1 Answers1

7

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:

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1
    just a polite inquiry ..is this more efficient than the non-linq version ? Why /Why not ? – ashutosh raina Oct 04 '11 at 07:24
  • @ashutoshraina: I doubt it makes a huge difference. It it's important, measure the performance of both. I'd expect the non-LINQ version to be slightly faster, but I'm not 100% sure. – Mark Byers Oct 04 '11 at 07:30
  • 1
    @Mark Why you changed back the `==` I had put after `c.Name`? Is there something I don't know? – xanatos Oct 04 '11 at 07:36
  • @xanatos: Sorry it was an accident - I originally typoed when writing my first answer and when I later edited it to improved the wording it accidentally reverted your correction. Thanks for trying to fix it. I've corrected it now. – Mark Byers Oct 04 '11 at 07:37