ListA的RemoveAt方法不起作用

时间:2014-05-19 10:06:33

标签: c#

这是我的列表类

 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));
    }
 }

我也试过了简单的删除方法

2 个答案:

答案 0 :(得分:0)

也许您应该使用.Contains方法首先检查......

foreach (ModuleAllocation moduleAllocation in ClosedProject.ModuleList)
 {
   if (moduleAllocation != null)
   {
       if (ModuleAllocationContainer.Contains(moduleAllocation))
        ModuleAllocationContainer.RemoveAt(ModuleAllocationContainer.IndexOf(moduleAllocation));
    }
 }

否则,您正试图删除可能不在列表中的内容。

编辑:正如@Rawling指出的那样,你也可以......

foreach (ModuleAllocation moduleAllocation in ClosedProject.ModuleList)
 {
   if (moduleAllocation != null)
   {
       var indexOf = ModuleAllocationContainer.IndexOf(moduleAllocation);
       if (indexOf != -1)
          ModuleAllocationContainer.RemoveAt(indexOf);
    }
 }

答案 1 :(得分:0)

您可以尝试使用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