C
C#2y ago
KQ

❔ Transform foreach to LINQ for optimization

is there a way to transform this logic from foreach to LINQ? I'm talking about the two foreaches. Thank you List<JobEntity> JobsToSync = await this.JobsReppository.GetAllQueryable() .Where(x => x.IsSyncedWithServer == false) .ToListAsync(); foreach (JobEntity jobEntityToSync in JobsToSync) { List<PictureEntity> Images = jobEntityToSync.Images.ToList(); foreach (PictureEntity image in Images) { //some logic } }
15 Replies
ero
ero2y ago
You put "for optimization" in your title. Using Linq will in almost all cases unoptimize your code.
Anton
Anton2y ago
maybe they mean complexity rather than perf take a loot at SelectMany
KQ
KQOP2y ago
so you mean that from a time complexity/performance POV, foreach > LINQ?
ero
ero2y ago
Yes
KQ
KQOP2y ago
okay, then I've been lied to Kekw thanks for the clarification
ero
ero2y ago
And for > foreach
KQ
KQOP2y ago
thank you
Esa
Esa2y ago
foreach is about as performant as it gets, but it's also as imperative as it gets.
KQ
KQOP2y ago
haha fun fact is I also remembered that for>foreach>linq but I got gaslit to think otherwise
Esa
Esa2y ago
My point is performance is not always a valid concern. Sure, the difference between LINQ and for is relatively big, but very few of us perform tasks where that performance delta is the difference between good enough and insufficient.
KQ
KQOP2y ago
I understand
ero
ero2y ago
Yeah you probably don't care, especially not for database stuff Where the database round-trip is what, 16ms? That's plenty of time
Esa
Esa2y ago
20-50 in wfh times I'd wager
cumslvt13
cumslvt132y ago
using linq here you can only flatten the result via SelectMany() If you don't really need job entity itself, you can query only images: var images = await dbContext.Jobs.SelectMany(j => j.Images).ToListAsync()
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server