在对象的列表替换对象 [英] Replace a object in a list of objects
问题描述
在C#中,如果我有一个列表< T>
,我有类型的对象 T
,我怎么能在更换特定项目的列表< T>
同类型的对象 T
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
?
下面是我曾尝试:
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;
在上面的代码,我想替换 customListItem2
与 newCustomListItem
。
In the above code, I want to replace the customListItem2
with the newCustomListItem
.
我必须删除列表中的项目,然后插入新物品?我不能做 customListItem2 = 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?
在此先感谢
推荐答案
你必须更换的项目,而不是 customListItem2
的价值。只需更换如下:
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;
通过这样的:
customListItem2 = customListItems.Where(i=> i.name == "Item 2").First();
var index = customListItems.IndexOf(customListItem2);
if(index != -1)
customListItems[index] = newCustomListItem;
编辑:
由于罗马R. 在评论中所述,您可以替换。凡(谓语)。首先()
通过一个简单的第一(谓语)
:
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");
这篇关于在对象的列表替换对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!