Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# linq where on object lists incredibly slow

i have a setup that looks like this

foreach(Master m in masters){
   m.details = allDetails.Where(d => d.ID == m.detailID).ToList();
}

masters and AllDetails are just Lists of objects, no actual SQL being run here. I did that earlier. I actually didnt write a "normal" sql join query, because i expected this way to be rather fast...

This runs incredibly slow, as in 20s+ for like 20k master entries.

I know i must be missing something incredibly obvious, but i just cant figure out what. Whats the way to solve this super common problem?

like image 806
DFENS Avatar asked Nov 15 '25 18:11

DFENS


1 Answers

For each Master you iterate through the whole allDetails list. You should use grouping and create a dictionary:

var detailsPerMaster = allDetails.GroupBy(d => d.ID)
                                 .ToDictionary(g => g.Key, g => g.ToList());

Then you can set your details properties:

foreach(Master m in masters)        
    m.details = detailsPerMaster[m.detailID];

Or to better match your results:

foreach(Master m in masters)            
    m.details = detailsPerMaster.TryGetValue(m.detailID, out var list) ? list : new List<--detailTypeHere-->();
like image 63
René Vogt Avatar answered Nov 17 '25 10:11

René Vogt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!