Change item in collection with LINQ
17,875
Solution 1
LINQ is a querying language, it should keep the original collection immutable.
This is ok
foreach (var item in allCars.Where(c => c.Model == "Colt"))
{
item.Model = "Dart";
}
Please read this post on why it is not implemented in LINQ
Solution 2
foreach(var item in allCars.Where(c => c.Model == "Colt"))
{
item.Model = "Dart";
}
Author by
coson
Updated on June 16, 2022Comments
-
coson almost 2 years
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 this:
for (var item in allCars.Select(c => c.Model == "Colt")) { item.Model = "Dart"; }
Or this:
allCars.Single(c => c.Model == "Colt").Model = "Dart";
But how about modifying the item "in-place" in the list?
The last way I mentioned will work fine if I have one property to modify, but what if I have two?
-
Leonardo Wildt about 8 yearsThis is really rad, i appreciate the idea of having the collection remain immutable while still being able to change the item names. This answer really helped me out today!
-
Emre Kantar over 7 yearsCompiler does not allow to do this. It gives an error.
Cannot modify members of 'item' because it is a 'foreach iteration variable
-
Flynn1179 over 7 years@EmreKantar: This is true if the type of the iteration variable is a struct. In the OP's question, it's a class, and this solution will work.