Best way to update an element in a generic List [duplicate]
Solution 1:
AllDogs.First(d => d.Id == "2").Name = "some value";
However, a safer version of that might be this:
var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }
Solution 2:
You could do:
var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));
This will return the matching dog, else it will return null
.
You can then set the property like follows:
if (matchingDog != null)
matchingDog.Name = "New Dog Name";