Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Linq's GroupBy method has a deferred execution?

Tags:

c#

linq

group-by

I've found this question, but it has no answer yet... What algorithm does Linq GroupBy use?

Since you have to iterate over the entire source collection to know all the groups, how can its execution be deferred? Will it iterate the source collection only once? Does it use a buffer?

like image 947
lmcarreiro Avatar asked Jan 06 '23 02:01

lmcarreiro


1 Answers

(I'm assuming we're only talking about LINQ to Objects.)

It's still deferred in that until you start asking for results, it won't read the source collection at all. But yes, once you ask for the first result, it will indeed read the whole collection. It only reads the source once, and it only asks each element for its grouping key once. All the results are buffered in memory, as you suspected.

My Edulinq blog post on GroupBy (Edulinq is basically a reimplementation of LINQ to Objects for the sake of education) shows a sample implementation, although that's in terms of ToLookup.

like image 172
Jon Skeet Avatar answered Jan 07 '23 15:01

Jon Skeet