# ラムダ式/LINQ

## ラムダ式

`using System;`が必要

```Func<int, int> mul = x => x * x;
Debug.Log("[Func] mul: " + mul(5));
```

```Action<int, int> sum = (x, y) => {
int t = x + y;
Debug.Log("[Action] sum: " + t);
};
sum(2, 3);
```
デリゲート
```void Start() {
Action<int, int> delegateSum = Sum;
delegateSum(2,3);
}
void Sum(int x, int y) {
int t = x + y;
Debug.Log("[Delegate] sum: " + t);
}
```

## LINQ拡張メソッド

[C#] これだけ押さえておけば大丈夫！？LINQ拡張メソッドまとめ

`using System.Linq;`が必要

```IEnumerable<int> scores = Enumerable.Range(1, 10);
```

```var oddNums = scores
.Where(score => score % 2 != 0)
.OrderByDescending(score => score)
.Take(3);

oddNums.ToList().ForEach(num => Debug.Log("上位3つの奇数 => " + num));
```

```var minOddNum = scores
.OrderBy(score => score)
.First(score => score % 2 != 0);

Debug.Log("最小の奇数 => " + minOddNum);
```
[pattern1]最大の奇数
```var maxOddNum1 = scores
.OrderBy(score => score)
.Last(score => score % 2 != 0);

Debug.Log("[pattern1]最大の奇数 => " + maxOddNum1);
```
[pattern2]最大の奇数
```var maxOddNum2 = scores
.Where(score => score % 2 != 0)
.Max();

Debug.Log("[pattern2]最大の奇数 => " + maxOddNum2);
```
[pattern1]最初と最後を除く数を10で割る
```var filteredNums1 = scores
.Where((score, index) => index != 0 && index != scores.Count() - 1)
.Select(score => (float)score / 10);

filteredNums1.ToList().ForEach(num => Debug.Log("[pattern1]最初と最後を除く数を10で割る => " + num));
```
[pattern2]最初と最後を除く数を10で割る
```var filteredNums2 = scores
.Skip(1)
.Reverse()
.Skip(1)
.Reverse()
.Select(score => (float)score / 10);

filteredNums2.ToList().ForEach(num => Debug.Log("[pattern2]最初と最後を除く数を10で割る => " + num));
```