合并两个不同类型的列表 [英] 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);
}
这很好用.但是,这需要花费很长时间,因为两个列表都变得非常大(在lstA中大约为70k,在lstB中为大约2000k).
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).
我想知道是否有更快或更有效的方式来完成我所需要的?也许使用LINQ?
I was wondering if there is a faster or more efficient way to accomplish what I need? Maybe with LINQ?
推荐答案
您可以使用O(n)
复杂度来代替O(N²)
使用Join()
:
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
和Join
操作使用哈希,因此它们应靠近O(N)
而不是O(N²)
.
Distinct
, GroupBy
and Join
operations use hashing, so they should be close to O(N)
instead of O(N²)
.
这篇关于合并两个不同类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文