Search code examples
c#linqupdating

How to update an item in a list keeping the rest of the list intact through Linq


Say we have a list,

Dog d1 = new Dog("Fluffy", "1");
Dog d2 = new Dog("Rex", "2");
Dog d3 = new Dog("Luna", "3");
Dog d4 = new Dog("Willie", "4");

List<Dog> AllDogs = new List<Dog>()
AllDogs.Add(d1);
AllDogs.Add(d2);
AllDogs.Add(d3);
AllDogs.Add(d4);

If I want to update d4, from its name from willie to wolly. I want to return a list with all dogs with an update for d4.

I am trying something like this :

var dog = AllDogs.Where(d => d.Id == "2").FirstOrDefault();
if (dog != null) { dog.Name = "some value"; }

But this returns only the updated item, I want the whole list which includes the updated item.


Solution

  • Here's the functional way to do it. This creates a new list with new dogs. This works with any IEnumerable<Dog>

    var dogs = AllDogs.Select(s => 
      new Dog() { Id = s.Id, Name = (s.Id == "2" ? "some value" : s.Name) });
    

    Here's a way to edit the list in place without creating any new objects. This works only with List<Dog>

    AllDogs.ForEach(f => f.Name = (f.Id == "2" ? "some value" : f.Name));