Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a object in a list of objects

In C#, if I have a List<T>, and I have an object of type T, how can I replace a specific item in the List<T> with the object of type T?

Here is what I have tried:

List<CustomListItem> customListItems = new List<CustomListItem>(); CustomListItem customListItem1 = new CustomListItem() { name = "Item 1", date = DateTime.MinValue}; CustomListItem customListItem2 = new CustomListItem() { name = "Item 2", date = DateTime.MinValue }; CustomListItem customListItem3 = new CustomListItem() { name = "Item 3", date = DateTime.MinValue };  customListItems.Add(customListItem1); customListItems.Add(customListItem2); customListItems.Add(customListItem3);  CustomListItem newCustomListItem = new CustomListItem() { name = "Item 4", date = DateTime.Now };  customListItem2 = customListItems.Where(i=> i.name == "Item 2").First(); customListItem2 = newCustomListItem; 

In the above code, I want to replace the customListItem2 with the newCustomListItem.

Do I have to remove the item in the list, and then insert the new item? Can I not do a simple assignment of customListItem2 = newCustomListItem?

What is the most efficient way of replacing an item in a list with another item?

Thanks in advance

like image 917
user3736648 Avatar asked Nov 05 '14 08:11

user3736648


People also ask

How do you replace an object in a list?

The easiest way to replace an item in a list is to use the Python indexing syntax. Indexing allows you to choose an element or range of elements in a list. With the assignment operator, you can change a value at a given position in a list.

How do you replace multiple elements in a list in Python?

Replace Multiple Values in a Python List. There may be many times when you want to replace not just a single item, but multiple items. This can be done quite simply using the for loop method shown earlier.

How do you replace data in a list in flutter?

If you know the index of the element you want to replace, you don't need to remove existing element from the List. You can assign the new element by index. Show activity on this post.


1 Answers

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"); 
like image 179
Abbas Avatar answered Sep 21 '22 06:09

Abbas