在 C# 中搜索匹配給定條件的元素並返回整個 List 中最後一次出現的基於 0 的索引


搜尋匹配條件的元素並返回整個 List 中最後一次出現的基於 0 的索引的程式碼如下 −

示例

 現場演示

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i) {
      return ((i % 10) == 0);
   }
   public static void Main(String[] args) {
      List<int> list = new List<int>();
      list.Add(200);
      list.Add(215);
      list.Add(310);
      list.Add(500);
      list.Add(600);
      Console.WriteLine("List elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Last Index of the satisfying condition = "+list.FindLastIndex(demo));
   }
}

輸出

輸出結果如下 −

List elements...
200
215
310
500
600
Last Index of the satisfying condition = 4

示例

下面我們來看另一個示例 −

 現場演示

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i) {
      return ((i % 2) == 0);
   }
   public static void Main(String[] args) {
      List<int> list = new List<int>();
      list.Add(200);
      list.Add(215);
      list.Add(310);
      list.Add(500);
      list.Add(655);
      Console.WriteLine("List elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Last Index of the satisfying condition = "+list.FindLastIndex(demo));
   }
}

輸出

輸出結果如下 −

List elements...
200
215
310
500
655
Last Index of the satisfying condition  = 3

更新於:2019 年 12 月 16 日

160 次瀏覽

開啟您的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.