簡體   English   中英

更改添加到列表的項目(AddRange)更改添加到AddRange的表

[英]Items added to List (AddRange) are changed when the table added to AddRange is changed

我希望如果在循環外啟動臨時列表會發生這種情況,但是我不是很不明白為什么我得到了我想要的結果。 我的代碼本質上是:

foreach (DataRow dtRow in dt.Rows)
{
    List<IItemData> tempTable = new List<IItemData>();
    tempTable = CreateCopyOfTemplate(item, new List<IItemData>(), tableTemplate, itemDataList, item.Id, tableSortOrder);

    foreach (IItemData itemData in tempTable)
    {
        if (itemData.Content.StartsWith("cdt:") && itemData.DataSource.Description == nameof(DataSource.CustomDataTableValue))
        {
            itemData.Content = dtRow[itemData.Content.Replace("cdt:", "")].ToString();
        }
    }

    tableSortOrder++;
    itemDataList.AddRange(tempTable.ToList());
}


private static List<IItemData> CreateCopyOfTemplate(IItemData itemData, List<IItemData> newTable, List<IItemData> templateTable, List<IItemData> originalTable, int? origParentId, int tableSortOrder)
{
    List<IItemData> childList = templateTable.Where(x => x.ParentId == origParentId).ToList();

    if (itemData.DataSource != null && itemData.DataSource.Description == nameof(DataSource.CustomDataTable))
    {
        itemData.Id = originalTable.Max(x => x.Id) + 1;
        itemData.SortOrder = tableSortOrder;
        newTable.Add(itemData);
    }

    foreach (IItemData childItem in childList)
    {
        origParentId = childItem.Id;
        childItem.ParentId = itemData.Id;
        childItem.Id = newTable.Max(x => x.Id) + 1;
        newTable.Add(childItem);

        CreateCopyOfTemplate(childItem, newTable, templateTable, originalTable, origParentId, tableSortOrder);
    }

    return newTable;
}

在ForEach循環的每個遍歷中的什么地方,我創建一個名為tempTable的新List<IITemData> 我用一種方法填充它,然后再將其添加到另一個名為itemDataList的List的Range中。

我首先在循環內啟動了tempTable列表,並且在應用於主列表時也使用了ToList(),但是在循環的第一遍添加的記錄都用循環的第二遍的值進行了更新-因此最終得到我列表中的重復數據!

我感覺到我缺少明顯的東西,但這已經是漫長的一天,只是無法弄清楚。

因此,我不確定100%,但是您似乎在foreach循環的每個遍歷中都在重復使用“ item”對象,您在CreateCopyOfTemplate中對其進行了一些更改,然后將其添加到newTable並返回它。 只是要再次傳遞它,進行一些更改然后將其返回。 最終使用相同的參考

if (itemData.DataSource != null && itemData.DataSource.Description == nameof(DataSource.CustomDataTable))
{

    itemData.Id = originalTable.Max(x => x.Id) + 1;
    itemData.SortOrder = tableSortOrder;
    newTable.Add(itemData); <-- Here you keep adding the same item
}

您可以實例化實現IItemData的對象的新實例,並改用它。 一種簡單的方法可能是將對象深復制到那里,或者只是手動設置所有屬性。

看這里: https : //docs.microsoft.com/zh-cn/dotnet/api/system.object.memberwiseclone?view=netframework-4.7.2

暫無
暫無

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

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