LoginSignup
1
5

More than 5 years have passed since last update.

ラムダ式/LINQ

Last updated at Posted at 2017-10-23

ラムダ式

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

参考
【Unity】ラムダ式を実装する
C#でデリゲートとラムダ式を使ってみる

LINQ拡張メソッド

[C#] これだけ押さえておけば大丈夫!?LINQ拡張メソッドまとめ
基本的にはこちらを見ればよい

以下、使用例。

using System.Linq;が必要

準備
IEnumerable<int> scores = Enumerable.Range(1, 10);
上位3つの奇数
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));
1
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5