简体   繁体   English

合并两个不同类型的列表

[英]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).然而,这需要很长时间,因为两个列表都变得非常大(lstA 中大约有 70k 个项目,lstB 中大约有 20k 个项目)。

I was wondering if there is a faster or more efficient way to accomplish what I need?我想知道是否有更快或更有效的方法来完成我的需要? Maybe with LINQ?也许用 LINQ?

You can do it with O(n) complexity instead of O(N²) with Join() :您可以使用O(n)复杂度而不是使用Join()O(N²)来做到这一点:

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²) . DistinctGroupByJoin操作使用散列,所以它们应该接近O(N)而不是O(N²)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM