Search code examples
c#asp.netlistgenerics

How to update a List<> item's property 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.

How can I do this?


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;