Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Biểu thức Lambda (Lambda Expressions) trong C#

Lambda expression mô tả một mẫu, có token => (đọc "goes to") trong ngữ cảnh biểu thức.

Ví dụ

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

Kết quả

Index: 2

Dùng "goes to" => tìm index số chẵn đầu tiên: list.FindIndex(x => x % 2 == 0). Index 2 = phần tử thứ 3 (40).