比较两个列表并按特定条件添加缺少的项目

时间:2017-02-02 12:09:51

标签: c# list c#-4.0 parallel-processing compare

我写了如下代码:

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

我正在尝试根据下一个标准向missingList和ListToUpdate添加项目:

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来加快速度......

有人能帮助我吗?

2 个答案:

答案 0 :(得分:2)

让我们使用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);
        }
    });

上面的代码使用了两个嵌套的并行列表迭代器。

答案 1 :(得分:1)

以下是比较两个列表的示例,这些列表将为您提供新ID列表。

我用来保存数据的类

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