什麼是 C# 中的 Lambda 表示式?


C# 中的 Lambda 表示式用來描述一個模式。它有一個令牌 => 在一個表示式上下文中。這被讀作“轉至”運算子,並在宣告 Lambda 表示式時使用。

下面是一個關於如何使用 C# 中的 Lambda 表示式的示例 −

示例

 線上演示

using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      List<int> list = new List<int>() { 21, 17, 40, 11, 9 };
      int res = list.FindIndex(x => x % 2 == 0);
      Console.WriteLine("Index: "+res);
   }
}

輸出

Index: 2

以上,我們看到了如何使用“轉至”運算子來找到偶數的索引 −

list.FindIndex(x => x % 2 == 0);

以上示例會產生以下輸出。

Index: 2

偶數位於索引 2 處,即它是第 3 個元素。

更新於: 20-6-2020

206 次瀏覽

開始你的 職業生涯

完成該課程即可獲得認證

開始
廣告
© . All rights reserved.