I’m running throuth Microsoft’s 101 LINQ Samples, and I’m stumped on how this query knows how to assign the correct int value to the correct int field:
public void Linq12()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) });
Console.WriteLine("Number: In-place?");
foreach (var n in numsInPlace)
{
Console.WriteLine("{0}: {1}", n.Num, n.InPlace);
}
}
I saw in SO #336758 that there have been errors in the examples before, but it is much more likely that I am just missing something.
Could someone explain this and how the compiler knows how to interpret this data correctly?
EDIT:
OK, I think my confusion comes from the LINQ extension that enables the Select feature to work. The Func and two int parameters IEnumerable<TResult> IEnumerable<int>.Select(Func<int,int,TResult> selector) are most likely the key to my lack of understanding.

I’m not really sure what you are asking of but the
Selectiterates over the list starting at index 0. If the value of the element at the current index is equal to the index it will set theInPlaceproperty in the anonymous object to true. My guess is that the code above prints true for 3, 6 and 7, right?It would also make it easier to explain if you write what you don’t understand.
Jon Skeet has written a series of blog post where he implement linq, read about
Selecthere: Reimplementation of SelectUPDATE: I noticed in one of your comment to one of the other comments and it seems like it is the lambda and not linq itself that is confusing you. If you read Skeet’s blog post you see that
Selecthas two overloads:The
Selectwith index matches the second overload. As you can see it is an extension ofIEnumerable<TSource>which in your case is the list ofintsand therefor you are calling theSelecton anIEnumerable<int>and the signature ofSelectbecomes:Select<int, TResult>(this IEnumerable<int> source, Func<int, int, TResult> selector). As you can see I changedTSourceagainstint, since that is the generic type of yourIEnumerable<int>. I still haveTResultsince you are using anonymous type. So that might explain some parts?