我写了如下代码:
foreach (var itemA in itm)
{
foreach (var itemB in filteredList)
{
if (itemA.ItemID != itemB.ItemID)
{
missingList.Add(itemB);
ListToUpdate.Add(itemB);
}
else
{
if (itemA.QuantitySold != itemB.QuantitySold)
{
ListToUpdate.Add(itemB);
}
}
}
}
如您所见,我这里有两个结构相同的列表,它们是:
List #1 is "itm" list - which contains old records from DB
List #2 is "filteredList" - which has all items from DB and + new ones
我正在尝试将项目添加到缺少列表和列表更新下一个条件:
All items that are "new" in filteredList - meaning their ItemID doens't exists in "itm" list should be added to missingList.
And all items that are new in filteredList- filteredList - meaning their ItemID doens't exists in "itm" list should be added to .ListToUpdate
And final criteria to add items to ListToUpdate should be those items that exist in both lists - and if the quantitysold in "itm" list is different - add them to ListToUpdate
我写的上面代码给了我完全错误的结果,我最终在两个列表中都有超过 50000 个额外的项目......
我想以我上面写的方式更改此代码,并可能使用并行循环或 PLINQ 来加快速度......
有人可以帮助我吗?
让我们使用 C# 4.0 中可用的 Parallel.ForEach:
Parallel.ForEach(filteredList, (f) =>
{
var conditionMatchCount = itm.AsParallel().Max(i =>
// One point if ID matches
((i.ItemID == f.ItemID) ? 1 : 0) +
// One point if ID and QuantitySold match
((i.ItemID == f.ItemID && i.QuantitySold == f.QuantitySold) ? 1 : 0)
);
// Item is missing
if (conditionMatchCount == 0)
{
listToUpdate.Add(f);
missingList.Add(f);
}
// Item quantity is different
else if (conditionMatchCount == 1)
{
listToUpdate.Add(f);
}
});
上面的代码使用两个嵌套的并行列表迭代器。
下面是一个比较两个列表的示例,这些列表将为您提供新 ID 的列表。
用于保存数据的 I 类
public class ItemList
{
public int ID { get; set; }
}
获取新 ID 的功能
private static void GetNewIdList()
{
List<ItemList> lstItm = new List<ItemList>();
List<ItemList> lstFiltered = new List<ItemList>();
ItemList oItemList = new ItemList();
oItemList.ID = 1;
lstItm.Add(oItemList);
lstFiltered.Add(oItemList);
oItemList = new ItemList();
oItemList.ID = 2;
lstItm.Add(oItemList);
lstFiltered.Add(oItemList);
oItemList = new ItemList();
oItemList.ID = 3;
lstFiltered.Add(oItemList);
var lstListToUpdate = lstFiltered.Except(lstItm);
Console.WriteLine(lstListToUpdate);
}
要获取常用 ID 列表,请使用以下内容
var CommonList = from p in lstItm
join q in lstFiltered
on p.ID equals q.ID
select p;
更新 2用于从基于ID的过滤列表中获取新ID列表
var lstListToUpdate2 = lstFiltered.Where(a => !lstItm.Select(b => b.ID).Contains(a.ID));