i’m trying to optimize this code:
foreach (string id in ids)
{
MyClass x = myDictionary[id];
foreach (var map in Maps)
{
if ( x.id == map.SourceId || x.id == map.DestionationId)
{
//add id to a hashset
}
}
}
if ids.count is 1600 and Maps.Count is 300 000 in takes around 10 minutes to process.
i’ve tried LINQ, but the results are not a lot better:
var allIds = Maps.select(map => map.SourceId).Union(Maps.select(map => map.DestinationID)).Distinct();
var toAdd = from id in Ids
join mapId in AllIds on id equals mapid
select id;
//create hashset based on toAdd collection.
Can anyone point me to a better solution and if possible explain why linq in this case isn’t much more faster?
Thanks
You have complexity of O(countIds * countMaps), if you put all Maps into 2 dictionaries indexed by source and destination you’ll get O(countIds + countMaps).