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?
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-->();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With