簡體   English   中英

Linq - 獲取最后一個非零數組的索引

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

是否有Linq表達式返回數組中最后一個非零值的索引? 我對擴展感興趣,只是一個簡單的linq表達式。

我在想像這樣的偽代碼:

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

返回值應為2;

您可以使用Array.FindLastIndex<T>方法:

int index = Array.FindLastIndex(myIntArray, 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();
    }
}

輸出: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