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

C#asp.netListGenerics

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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;

Solution 2 - C#

Just to add to CKoenig's response. His answer will work as long as the class you're dealing with is a reference type (like a class). If the custom object were a struct, this is a value type, and the results of .FirstOrDefault will give you a local copy of that, which will mean it won't persist back to the collection, as this example shows:

struct MyStruct
{
	public int TheValue { get; set; }
}

Test code:

List<MyStruct> coll = new List<MyStruct> {
			                                new MyStruct {TheValue = 10},
			                                new MyStruct {TheValue = 1},
			                                new MyStruct {TheValue = 145},
			                                };
var found = coll.FirstOrDefault(c => c.TheValue == 1);
found.TheValue = 12;

foreach (var myStruct in coll)
{
	Console.WriteLine(myStruct.TheValue);
}
Console.ReadLine();

The output is 10,1,145

Change the struct to a class and the output is 10,12,145

HTH

Solution 3 - C#

or without linq

foreach(MyObject obj in myList)
{
   if(obj.prop == someValue)
   {
     obj.otherProp = newValue;
     break;
   }
}

Solution 4 - C#

Can also try.

 _lstProductDetail.Where(S => S.ProductID == "")
        .Select(S => { S.ProductPcs = "Update Value" ; return S; }).ToList();

Solution 5 - C#

var itemIndex = listObject.FindIndex(x => x == SomeSpecialCondition());
var item = listObject.ElementAt(itemIndex);
item.SomePropYouWantToChange = "yourNewValue";

Solution 6 - C#

You can do somthing like :

if (product != null) {
	var products = Repository.Products;
	var indexOf = products.IndexOf(products.Find(p => p.Id == product.Id));
	Repository.Products[indexOf] = product;
	// or 
	Repository.Products[indexOf].prop = product.prop;
}

Solution 7 - C#

This was a new discovery today - after having learned the class/struct reference lesson!

You can use Linq and "Single" if you know the item will be found, because Single returns a variable...

myList.Single(x => x.MyProperty == myValue).OtherProperty = newValue;

Solution 8 - C#

I found a way of doing it in one Line of code unsing LINQ:

yourList.Where(yourObject => yourObject.property == "yourSearchProperty").Select(yourObject => { yourObject.secondProperty = "yourNewProperty"; return yourObject; }).ToList();

Solution 9 - C#

var index = yourList.FindIndex(x => x.yourProperty == externalProperty);
if (index > -1)
{
   yourList[index] = yourNewObject;   
}

yourlist now has the updated object inside of it.

Solution 10 - C#

//Find whether the element present in the existing list

    if (myList.Any(x => x.key == "apple"))
       {
          //Get that Item
         var item = myList.FirstOrDefault(x => x.key == ol."apple");
        //update that item
         item.Qty = "your new value";
       }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBurjuaView Question on Stackoverflow
Solution 1 - C#Random DevView Answer on Stackoverflow
Solution 2 - C#Matt RobertsView Answer on Stackoverflow
Solution 3 - C#ErixView Answer on Stackoverflow
Solution 4 - C#BJ PatelView Answer on Stackoverflow
Solution 5 - C#codeMonkeyView Answer on Stackoverflow
Solution 6 - C#HalimiView Answer on Stackoverflow
Solution 7 - C#DaveView Answer on Stackoverflow
Solution 8 - C#MrJockelView Answer on Stackoverflow
Solution 9 - C#Mo D GenesisView Answer on Stackoverflow
Solution 10 - C#user16187988View Answer on Stackoverflow