簡體   English   中英

清單 <T> .Remove(T item)從原始列表中刪除項目

[英]List<T>.Remove(T item) removing item from original List

我有以下代碼

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

因此,當整數d在點類型的XY之間時,它將被從臨時列表中刪除,因為下一個d不必檢查相同的_tempPointList元素。 但是當代碼到達_tempPointList.Remove(point); point元素已從_tempPointList_pointList ,我感到很奇怪。 為什么還要從主列表中刪除呢?

因為您正在使用相同的列表。 您實際上是在此行中為_tempPointList分配了相同的實例(並刪除了在上一行中創建的原始_tempPointList的引用。):

_tempPointList = _pointList;

我建議您通過使用此調用直接復制列表來實例化副本列表:

var _tempPointList = new List<Point>(_pointList); //creates a shallow copy

我看到了另一個問題:您正在遍歷列表時從列表中刪除元素。 繼續進行迭代時,是否沒有收到System.InvalidOperationException

我可以通過遍歷原始列表並從副本列表中刪除來解決此問題,如下所示:

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;

}

正如您的問題評論中提到的endend一樣,您可以僅在List.RemoveAll()上使用謂詞,如果謂詞返回true,則該謂詞將刪除項目。 我沒有測試性能,但可以自由比較。

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

您將需要復制列表以使邏輯起作用。

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

// make a copy like this
var _tempPointList = new List<Point>(_pointList);

否則,您剛剛復制了對列表的引用,並且_tempPointList_pointList指向同一內存

您遇到此問題是因為_tempPointList和_pointList具有相同的引用,因此,當您修改一個列表時,另一個列表會被自動修改。 您遇到的另一個問題是Foreach,在使用Foreach遍歷列表時,無法簡化列表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM