[SOLVED] How to update an object in a List<> in C#

Issue

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?

Solution

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;

Answered By – Random Dev

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *