Tobi o' Bobi
Tobi o' Bobi

Reputation: 197

Merge two Lists of different types

I add data to the objects of a List from another List:

public void MergeLsts(List<A> lstA, List<B> lstB)
{
    foreach (A dataA in lstA)
    {
        foreach (B dataB in lstB)
        {
            if (dataA.ItemNo == dataB.ItemNo)
            {
                //dataA.ItemDescription is up to this point empty!
                dataA.ItemDescription = dataB.ItemDescription;
            }
        }
    }
    DoSomethingWithTheNewLst(lstA);
}

This works perfectly fine. However it takes pretty long because both lists get quite large (around 70k items in lstA and 20k items in lstB).

I was wondering if there is a faster or more efficient way to accomplish what I need? Maybe with LINQ?

Upvotes: 3

Views: 2257

Answers (1)

Vadim Martynov
Vadim Martynov

Reputation: 8892

You can do it with O(n) complexity instead of O(N²) with Join():

var joinedData =  dataA.Join(dataB, dA => dA.ItemNo, dB => dB.ItemNo, (dA, dB) => new { dA, dB }));
foreach(var pair in joinedData)
{
    pair.dA.ItemDescription = pair.dB.ItemDescription;
}

Distinct, GroupBy and Join operations use hashing, so they should be close to O(N) instead of O(N²).

Upvotes: 4

Related Questions