Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 892
Burjua Avatar asked Aug 25 '11 12:08

Burjua


1 Answers

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; 
like image 60
Random Dev Avatar answered Oct 01 '22 15:10

Random Dev