C# / LINQ fastest way of comparing two lists and assigning value

I have made a code which basically compares two lists in C#. First list contains properties like this:

  • ItemID
  • TotalViews

First list lacks values for TotalViews so I'm assigning them from 2nd list which has these props:

  • ItemID
  • HitCount // this is property for TotalViews that needs to be assigned

The code is as following:

foreach (var item in parsedMerchantData)
{
    var itemInB = HitCountItemIDS.FirstOrDefault(x => x.ItemID == item.ItemID);
    if (itemInB != null)
    {
        if (itemInB.HitCount != -1)
        {
            item.TotalViews = itemInB.HitCount;
        }
        else
        {
            item.TotalViews = 0;
        }
    }
}

Is there any more efficient way to write this using LINQ or implementing a custom comparer which would work faster on larger lists that contains sometimes 100000 items in themselves?

Jon Skeet
people
quotationmark

This is like jdweng's answer, but slightly simpler and it won't throw an exception for missing item IDs:

var hitCountsById = HitCountItemIDS.ToDictionary(x => x.ItemID, x => x.HitCount);
foreach (var item in parsedMerchantData)
{
    int hitCount;
    // We don't care about the return value of TryGetValue here...
    hitCountsById.TryGetValue(item.ItemID, out hitCount);
    item.HitCount = hitCount == -1 ? 0 : hitCount;
}

This should be O(N+M) where N is the size of HitCountItemIDs and M is the size of parsedMerchantData... so should as the data gets bigger, it should grow more slowly than the merge-sort approach, and is definitely simpler code. (It doesn't require comparing item ID for ordering, either - just equality.)

people

See more on this question at Stackoverflow