RemoveAt()不工作c#

Eri*_*tia 2 c# list removeclass removeall

即使在RemoveAt()方法之后,我的列表也保持不变,我甚至没有收到错误:

foreach (var row in queryCandidates.ToList())
{
    try
    {
        xString = queryCandidates.ToList().ElementAt(i).District;
        int.TryParse(xString, out xNumber);

        temp = xNumber.Equals(districtNumber);
        System.Diagnostics.Debug.Write(temp+ " ");
        System.Diagnostics.Debug.Write(i+" ");
        if (temp == false)
        {
            System.Diagnostics.Debug.WriteLine(" i is:"+i);

            //not working even when it should
            queryCandidates.ToList().RemoveAt(i);

        }
    }

    catch { }
    i++;
    if (last == i)
    {
        System.Diagnostics.Debug.WriteLine("before ending loop: ");
        return View(queryCandidates.ToList());
    }
}

System.Diagnostics.Debug.WriteLine("after ending the loop: ");
return View(queryCandidates.ToList());
Run Code Online (Sandbox Code Playgroud)

Dan*_*rth 7

ToList()创建一个新实例.从这个实例中删除元素.您没有从原始可枚举中删除该元素.

你应该做这样的事情:

var candidates = queryCandidates.ToList();
var elementsToRemove = new List<int>();
foreach (var row in candidates)
{
    // ...
    xString = candidates[i].District;
    // ...
    if (temp == false)
    {             
        // ... 
        elementsToRemove.Add(i);
    }  
}

for(int i = elementsToRemove.Count - 1; i >= 0; --i)
    candidates.RemoveAt(elementsToRemove[i]);

return View(candidates);
Run Code Online (Sandbox Code Playgroud)

请注意使用elementsToRemove.您无法直接在循环中删除项目.这将抛出异常.


此外,请注意ToList复制所有数据.每次你打电话给它.很明显,这不是一个循环中做的好主意.