於 C# 3.0 開始提供, 可以使用 lambda 運算式來建立匿名函數, 型式如下
運算式 lamdba
(參數) => 運算式
例: (a, b) => a + b
陳述式 lambda
(參數) => { 一連串的陳述式 }
例:
(a, b) =>
{
int c = a + b;
Console.WriteLine($"a + b = {C}")
}
任何 Lambda 運算式可轉換成 Delegate(委派)型別, 如果 Lambda 運算式沒有回傳值, 可以轉換成 Action 委派型別, 否則可轉換成其中一個 Func 委派型別
Action<string> greet = name =>
{
string greeting = $"Nice to meet you {name}";
Console.WriteLine(greeting);
};
greet("Marlon");
Func<int, int> square = x => x * x;
Console.WriteLine(square(12));
運算樹(expression tree)
運算式 lambda 也可以轉換成運算式樹
using System.Linq.Expressions
Expression<Func<int, int>> e = x => x * x;
Console.WriteLine(e);
// x => (x * x)
lambda expression 搭配 Linq 使用
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
int[] numbers = {5, 6, 3, 2, 1, 7, 8, 234, 54, 14, 653, 3, 4, 5, 6, 7};
List<int> oddNumbers = numbers.Where(n => n % 2 == 1).ToList();
Console.WriteLine(string.Join(", ", oddNumbers));
string[] catNames = {"Lucky", "Bella", "Luna", "Oreo", "Simba", "Toby", "Loki", "Oscar"};
double average = catNames.Average(cat => cat.Length);
double minCatName = catNames.Min(cat => cat.Length);
double maxCatName = catNames.Max(cat => cat.Length);
double sumCatName = catNames.Sum(cat => cat.Length);
Console.WriteLine(average);
Console.WriteLine(minCatName);
Console.WriteLine(maxCatName);
Console.WriteLine(sumCatName);
object[] mix = {1, "string", 'd', new List<int>() {1, 2, 3, 4}, new List<int>() {5, 2, 3, 4}, "dd", 's', "Hello Kitty", 1, 2, 3, 4};
var allIntegers = mix.OfType<int>().Where(i => i < 3);
Console.WriteLine(string.Join(", ", allIntegers));
var allIntList = mix.OfType<list<int>>().ToList();
for (int i = 0; i < allIntLists.Count; i++)
{
Console.WriteLine($"Int Lists[{i}]: " + string.Join(", ", allIntList[i]));
}