Replace a object in a list of objects
Solution 1:
You have to replace the item, not the value of customListItem2
. Just replace following:
customListItem2 = customListItems.Where(i=> i.name == "Item 2").First();
customListItem2 = newCustomListItem;
With this:
customListItem2 = customListItems.Where(i=> i.name == "Item 2").First();
var index = customListItems.IndexOf(customListItem2);
if(index != -1)
customListItems[index] = newCustomListItem;
Edit:
As Roman R. stated in a comment, you can replace the .Where(predicate).First()
by a simple First(predicate)
:
customListItem2 = customListItems.First(i=> i.name == "Item 2");
Solution 2:
var customListItems = new List<CustomListItem>();
var customListItem1 = new CustomListItem() { name = "Item 1", date = DateTime.MinValue };
var customListItem2 = new CustomListItem() { name = "Item 2", date = DateTime.MinValue };
var customListItem3 = new CustomListItem() { name = "Item 3", date = DateTime.MinValue };
customListItems.Add(customListItem1);
customListItems.Add(customListItem2);
customListItems.Add(customListItem3);
var newCustomListItem = new CustomListItem() { name = "Item 4", date = DateTime.Now };
customListItems[customListItems.FindIndex(x => x.name == "Item 2")] = newCustomListItem;
or
public static class ListExtensions
{
public static void Replace<T>(this List<T> list, Predicate<T> oldItemSelector , T newItem)
{
//check for different situations here and throw exception
//if list contains multiple items that match the predicate
//or check for nullability of list and etc ...
var oldItemIndex = list.FindIndex(oldItemSelector);
list[oldItemIndex] = newItem;
}
}
and then
customListItems.Replace(x => x.name == "Item 2", newCustomListItem);