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
question from:
https://stackoverflow.com/questions/26752909/replace-a-object-in-a-list-of-objects 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…