开发者

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 a开发者_如何学Goll 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.


as explained in this question you could have a look at the asymptotic complexity of the operations you're doing and see if you can redesign and somehow use a type of collection that offers less asymptotic complexity for those operations, or you could try if you can somehow divide the work among some threads or processes using the task parallel library as mentioned in this question.


You could also use the Union extension on List as it will avoid duplicates as long as your objects are comparable (or you have overriden GetHashCode)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜