列表的RemoveAt方法不起作用
本文关键字:不起作用 方法 RemoveAt 列表 | 更新日期: 2023-09-27 18:03:56
这是我的列表,class
public class ClosedProject : ViewModelBase
{
private string _projectId;
List<EmployeeOnProject> _employeeList;
List<ModuleAllocation> _moduleList;
}
下面的代码工作良好,即执行foreach循环后,employeeOnProject对象从EmployeeOnProjectContainer(employeeOnProject的列表)中删除
foreach (EmployeeOnProject employeeOnProject in ClosedProject.EmployeeList)
{
if (employeeOnProject != null)
{
EmployeeOnProjectContainer.RemoveAt(EmployeeOnProjectContainer.IndexOf(employeeOnProject));
}
}
foreach (ModuleAllocation moduleAllocation in ClosedProject.ModuleList)
{
if (moduleAllocation != null)
{
ModuleAllocationContainer.RemoveAt(ModuleAllocationContainer.IndexOf(moduleAllocation));
}
}
我也尝试过简单的删除方法
可以尝试使用Except()吗?
var list1 = new List<int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
var list2 = new List<int>(new int[] { 0, 2, 4 ,6, 8 });
var list3 = list1.Except(list2); // returns 1, 3, 5, 7, 9
也许您应该使用.Contains
方法先检查…
foreach (ModuleAllocation moduleAllocation in ClosedProject.ModuleList)
{
if (moduleAllocation != null)
{
if (ModuleAllocationContainer.Contains(moduleAllocation))
ModuleAllocationContainer.RemoveAt(ModuleAllocationContainer.IndexOf(moduleAllocation));
}
}
否则,您将尝试删除列表中可能不存在的内容。
EDIT:正如@Rawling指出的,你也可以做…
foreach (ModuleAllocation moduleAllocation in ClosedProject.ModuleList)
{
if (moduleAllocation != null)
{
var indexOf = ModuleAllocationContainer.IndexOf(moduleAllocation);
if (indexOf != -1)
ModuleAllocationContainer.RemoveAt(indexOf);
}
}