Dhinesh
Dhinesh

Reputation: 45

Linq- Indexed Select

        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);
        } 

What is index in the above linq query ? How it brings the index from the array ?

Upvotes: 0

Views: 1060

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500335

What is index in the above linq query ?

It's the index of the element being processed. So the first element (5) will have an index of 0, the second element (4) will have an index of 1 etc.

How it brings the index from the array ?

That's just what that overload of Select does:

The first argument to selector represents the element to process. The second argument to selector represents the zero-based index of that element in the source sequence. This can be useful if the elements are in a known order and you want to do something with an element at a particular index, for example. It can also be useful if you want to retrieve the index of one or more elements.

Although the real implementation of Select is a bit more complicated (I believe) it's logically implemented a bit like this:

public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, int, TResult> selector)
{
    // Method is split into two in order to make the argument validation
    // eager. (Iterator blocks defer execution.)
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (selector == null)
    {
        throw new ArgumentNullException("selector");
    }
    return SelectImpl(source, selector);
}

private static IEnumerable<TResult> SelectImpl<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, int, TResult> selector)
{
    int index = 0;
    foreach (TSource item in source)
    {
        yield return selector(item, index);
        index++;
    }
}

Upvotes: 4

Related Questions