简体   繁体   中英

Fastest way to navigate and add items to two different lists

I have 2 Lists of 2 different classes. We can call them Foo and Bar for this purpose. The List of Foos contains Bars that each Foo belongs to. The list of Bars contains all the Foos that the Bar belongs to.

I need a fast an efficient way of cycling through the two lists and adding each item to the other list.

I am currently using:

//  Add the List of Zones to the Vehicles
foreach (Foo foo in Program.data.Foos.list)
{
    foreach (Bar bar in Program.data.Bars.list)
    {
        bar.Foos.Add(foo);
        foo.Bars.Add(bar);
    }
} 

However, for my set of data I have ~5000 Foos and ~5000 Bars. This is tacking ~3 seconds to itterate through the other most foreach loop and appears to be rather inefficient.

Are there any faster ways to accomplish this? Possibly with Linq? What would you guys recommend to speed this up some more? Or have I hit a brick wall in terms of speed?

if bar.Foos and foo.Bars are properties then make an initial assigment for them before loop

var list1=bar.Foos; 
var list2=foo.Bars;

Giving an initial capacity for bar.Foos and foo.Bars would be good too.

您还可以在List上使用Union扩展名,因为只要您的对象是可比较的(否则您已覆盖GetHashCode),它将避免重复

bar.Foos = bar.Foos.Union(Program.data.Foos.list).ToList()

这个问题中所解释的,您可以查看正在执行的操作的渐近复杂度,看看是否可以重新设计并以某种方式使用为这些操作提供较少渐近复杂度的集合,或者可以尝试使用这个问题中提到的任务并行库以某种方式在某些线程或进程之间划分工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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