C# 列表<;T>;。删除(T项)从原始列表中删除项

C# 列表<;T>;。删除(T项)从原始列表中删除项,c#,.net,collections,C#,.net,Collections,我有以下代码 foreach (var d in dots) { var _tempPointList = new List<Point>(); _tempPointList = _pointList; foreach (var point in _tempPointList) { if (d >= point.X && d <= point.Y) { _tempPo

我有以下代码

foreach (var d in dots)
{
    var _tempPointList = new List<Point>();
    _tempPointList = _pointList;

    foreach (var point in _tempPointList)
    {
        if (d >= point.X && d <= point.Y)
        {
            _tempPointList.Remove(point);
        }
    }
}
foreach(变量d以点为单位)
{
var_tempPointList=新列表();
_tempPointList=_pointList;
foreach(临时点列表中的变量点)
{

如果(d>=point.X&&d,您需要制作一份列表副本,以便逻辑正常工作

// instead of this
var _tempPointList = new List<Point>();

// make a copy like this
var _tempPointList = new List<Point>(_pointList);
//而不是这个
var_tempPointList=新列表();
//像这样复印一份
var _tempPointList=新列表(_pointList);

否则,您刚刚复制了对列表的引用,并且
\u tempPointList
\u pointList
都指向相同的内存,因为您正在使用相同的列表。您在这一行中有效地为
\u tempPointList
分配了相同的实例(并删除对您在上一行中创建的原始
\u tempPointList
的引用):

我建议您通过此调用直接复制列表来实例化副本列表:

var _tempPointList = new List<Point>(_pointList); //creates a shallow copy
正如你问题的评论中提到的那样,如果返回true,你可以使用一个谓词删除一个项目。我没有测试性能,但是可以随意比较

foreach (var d in dots)
{
    _pointList.RemoveAll(point => d >= point.X && d <= point.Y);
}
foreach(变量d以点为单位)
{

_pointList.RemoveAll(point=>d>=point.X&&d您遇到了这个问题,因为_tempPointList和_pointList都有相同的引用,所以当您修改一个列表时,另一个列表会自动修改。另一个问题是Foreach在使用Foreach对列表进行迭代时无法对其进行moidify,因为两个实例都引用了相同的memory locationUse.RemoveAll()使用谓词,您将节省大量代码行。
foreach (var d in dots)
{
    var _tempPointList = new List<Point>(_pointList);

    foreach (var point in _pointList)
    {
        if (d >= point.X && d <= point.Y)
        {
            _tempPointList.Remove(point);
        }
    }

    _pointList = _tempPointList;

}
foreach (var d in dots)
{
    _pointList.RemoveAll(point => d >= point.X && d <= point.Y);
}