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.