How to update an object in a List<> in C#
I have a
List<> of custom objects.
I need to find an object in this list by some property which is unique and update another property of this object.
What is the quickest way to do it?
Using Linq to find the object you can do:
var obj = myList.FirstOrDefault(x => x.MyProperty == myValue); if (obj != null) obj.OtherProperty = newValue;
But in this case you might want to save the List into a Dictionary and use this instead:
// ... define after getting the List/Enumerable/whatever var dict = myList.ToDictionary(x => x.MyProperty); // ... somewhere in code MyObject found; if (dict.TryGetValue(myValue, out found)) found.OtherProperty = newValue;