use*_*648 27 .net c# list generic-list variable-assignment
在C#中,如果我有List<T>
,我有类型的对象T
,我怎么能在替换特定项目List<T>
类型的对象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;
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我想替换customListItem2
为newCustomListItem
.
我是否必须删除列表中的项目,然后插入新项目?我可以不做一个简单的任务customListItem2 = newCustomListItem
吗?
用另一个项目替换列表中项目的最有效方法是什么?
提前致谢
Abb*_*bas 44
您必须替换项目,而不是值customListItem2
.只需更换以下内容
customListItem2 = customListItems.Where(i=> i.name == "Item 2").First();
customListItem2 = newCustomListItem;
Run Code Online (Sandbox Code Playgroud)
有了这个:
customListItem2 = customListItems.Where(i=> i.name == "Item 2").First();
var index = customListItems.IndexOf(customListItem2);
if(index != -1)
customListItems[index] = newCustomListItem;
Run Code Online (Sandbox Code Playgroud)
编辑:
正如Roman R.在评论中所说,你可以用.Where(predicate).First()
一个简单的替换 First(predicate)
:
customListItem2 = customListItems.First(i=> i.name == "Item 2");
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
要么
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后
customListItems.Replace(x => x.name == "Item 2", newCustomListItem);
Run Code Online (Sandbox Code Playgroud)