❔ 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
You put "for optimization" in your title. Using Linq will in almost all cases unoptimize your code.
maybe they mean complexity rather than perf
take a loot at
SelectMany
so you mean that from a time complexity/performance POV, foreach > LINQ?
Yes
okay, then I've been lied to thanks for the clarification
And for > foreach
thank you
foreach is about as performant as it gets, but it's also as imperative as it gets.
haha fun fact is I also remembered that for>foreach>linq but I got gaslit to think otherwise
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.
I understand
Yeah you probably don't care, especially not for database stuff
Where the database round-trip is what, 16ms?
That's plenty of time
20-50 in wfh times I'd wager
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()
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.