【发布时间】:2019-01-28 23:11:55
【问题描述】:
如果我在循环之外启动我的临时列表,我希望会发生这种情况,但我不是那么不明白为什么我会得到我的结果。我的代码本质上是:
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 的列表的范围中。
我首先在循环中启动了 tempTable 列表,并且在应用到主列表时也使用了 ToList() 但是在循环的第一遍添加的记录全部更新为第二遍的值循环 - 因此在我的列表中出现重复数据!
我感觉我遗漏了一些明显的东西,但这是漫长的一天,我无法弄清楚。
【问题讨论】:
-
我认为您没有向我们展示足够的代码来确定实际问题是什么。阅读stackoverflow.com/help/mcve
-
我已经更新了我的完整代码...任何建议将不胜感激!