Linq索引选择 [英] Linq- Indexed Select

查看:92
本文介绍了Linq索引选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

上面的linq查询中的索引是什么?它是如何从数组中获取索引的?

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

推荐答案

上面的linq查询中的索引是什么?

What is index in the above linq query ?

它是要处理的元素的索引.因此,第一个元素(5)的索引为0,第二个元素(4)的索引为1等等.

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 ?

这就是 Select 的重载所做的工作:

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.

尽管Select的实际实现有些复杂(我相信),但它是逻辑上的实现,如下所示:

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

这篇关于Linq索引选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆