Friday, June 20, 2008

C# Puzzle No.7 (intermediate)

After two previous puzzles, you'll surely have no problems to determine the output of following code snippet without actually running it. Specifically, how many times the X will be printed?

List<int> list = new List<int>() { 1, 2, 3 };
list.GroupBy ( i => { Console.Write( "X" ); return i; } );
list.ToLookup( i => { Console.Write( "X" ); return i; } );
This Puzzle will let you think about differences (if any) between two seemingly identical methods, GroupBy and ToLookup.


stic said...


This one was nice - forced me to dig through the System.Linq Enumerable extension methods.

In both cases, an extension method is working on your list, which is first parameter of these methods. Whereas lambda expression is the second parameter of System.Func type.
However according to documentation there is a difference in execution of GroupBy (which is deferred) and ToLookup which will be executed immediately.
So we will get XXX - but from list.ToLookup only...
If we will got few lines more: IEnumerable {IGrouping{int, int}} o = list.GroupBy(i => { Console.Write("X"); return i; });

We will get XXX from GroupBy too ;-)

Wiktor Zychla said...

your remark about adding the enumerator (which eventually prints out XXX from BOTH statements) is of course correct.

however, I also think that it is interesting to note which Linq methods force immediate execution and which are deferred.

regarding the number of puzzles - there's no schedule. I hope to put a new puzzle from time to time but it's hard to come up with something interesting.

did you at least like puzzles 1-7?

stic said...

Of course, I like these.
Building application with it is really nice to focus on the language itself from time to time.

btw. Don't you think that the extension methods + overloads of these make it sometimes really hard to figure out what particular line of code is doing?
IMHO, C# is heading into Perl-like syntax with these expression :-]

Wiktor Zychla said...

Yes, I guess I would not be good at such puzzles myself.

I think I would rather give an incorrect answer at first and then I would be very surprized to learn the correct one ;)