简体   繁体   English

Linq - 获取最后一个非零数组的索引

[英]Linq - Get the Index of the Last Non-Zero Number of Array

Is there a Linq expression that returns the index of the last non-zero value in an array? 是否有Linq表达式返回数组中最后一个非零值的索引? I'm not interested in an extension, only a simple linq expression. 我对扩展感兴趣,只是一个简单的linq表达式。

I'm imagining something like this pseudo code: 我在想像这样的伪代码:

int index = {0, 2, 1}.LastOrDefaultAt(i => i > 0);

The returned value should be 2; 返回值应为2;

You can use the Array.FindLastIndex<T> method for this: 您可以使用Array.FindLastIndex<T>方法:

int index = Array.FindLastIndex(myIntArray, item => item > 0);

I notice that you mention "non-zero" rather than "greater than zero" in your question text. 我注意到你在问题文本中提到“非零”而不是“大于零”。 Should your predicate be: item => item != 0 ? 你的谓词应该是: item => item != 0

List<T>有一个名为FindLastIndex的扩展方法

var index = new int[] { 0, 2, 1}.ToList().FindLastIndex(x => x > 0);
class Program
{
    static void Main(string[] args)
    {
        int[] index = { 0, 2, 1 };

        var query = from p in index
                    where p != 0
                    orderby p descending
                    select p;

        Console.WriteLine(query.FirstOrDefault());
        Console.ReadKey();
    }
}

Output: 2. Could be written in method syntax if desired: 输出:2。如果需要,可以用方法语法编写:

var index = new int[] { 0, 2, 1 }.Where(a => a != 0).OrderByDescending(a => a).FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM