SelectMany is a fascinating operator in LINQ to Objects. For one thing, it is not as intuitive as most other LINQ operators. MSDN says that SelectMany “projects each element of a sequence to an IEnumerable(T) and flattens the resulting sequences into one sequence.” I still remember reading this description of SelectMany for the first time, [...]
I was discussing the little LINQ puzzle with Stephen Toub, and he brought up an idea which lead to another puzzle. I like this one even more than the previous one.
Why does the last line throw StackOverflowException?
IEnumerable<int> q = new int[] { 1, 2 };
q = from x in new int[] { 1, 2 }
[...]
Why does the last line hang?
IEnumerable<int> empty = Enumerable.Empty<int>();
for (int i = 0; i < 40; i++)
{
empty = empty.Concat(empty);
}
int[] emptyArray = empty.ToArray();
Answer in the comments section.
For a slightly harder challenge, check out the next puzzle.

Recent Comments