Change an item in a collection using LINQ

I have the following code:

List<Car> allCars = new List<Car>
{
    new Car(1977, "Ford", "Pinto"),
    new Car(1983, "Ford", "Taurus"),
    new Car(1981, "Dodge", "Colt"),
    new Car(1982, "Volkwagen", "Scirocco"),
    new Car(1982, "Dodge", "Challenger")
};

Array.ForEach(allCars.ToArray(), Console.WriteLine);

// I want to do an "in-place" modification of an item in 
// the list
var query = allCars.Select(x =>
{
    if (x.Model == "Colt") return "Dart";
});

public class Car
{
    public int Year { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }

    public Car(int year, string make, string model)
    {
       Year = year; Make = make; Model = model;
    }

    public override string ToString()
    {
        return string.Format("{0} - {1} {2}", Year, Make, Model);
    }
}

Now I know that I can do this:

var query = allCars.Select(c => c.Model == "Colt");

Or that:

for (var item in allCars.Select(c => c.Model == "Colt"))
{
    item.Model = "Dart";
}

Or that:

allCars.Single(c => c.Model == "Colt").Model = "Dart";

But what about changing the in-place item in the list?

The last method that I mentioned will work fine if I have one property to change, but what if I have two?

+5
source share
2 answers

LINQ is a query language; it must maintain an unchanged source collection.

This is normal

foreach (var item in allCars.Where(c => c.Model == "Colt"))
{
    item.Model = "Dart";
}

Please read this post about why it is not implemented in LINQ .

+12
source
foreach(var item in allCars.Where(c => c.Model == "Colt"))
{
    item.Model = "Dart";
}
+1
source

All Articles