LoginSignup
4
5

More than 5 years have passed since last update.

[C#] LINQについて忘れないように基礎的な機能をまとめておく

Last updated at Posted at 2018-07-11

LINQを使いたいと思ってもよく忘れてしまうのでよく使う機能をまとめる

そもそもLINQとは?

配列、リストなどに使える
繰り返し系の処理が見やすくなる(可読性向上)

機能一覧

要素絞り込み系

Select

要素に処理を行ない、その結果を返す

全て二乗される
var list = new List<int>(){1,2,3,4,5};
list.Select(c => c * c);
//=> 1 4 9 16 25

Where

条件を指定して要素を抽出

偶数のみ抽出
var list = new List<int>(){1,2,3,4,5};
list.Where(c => c % 2 == 0);
//=>2 4

OrderBy

指定内容で昇順ソートされたデータを返す

Ageでデータをソート
var array = new[] {
    new{Name = "A", Age = 1},
    new{Name = "C", Age = 2},
    new{Name = "B", Age = 1},
    new{Name = "E", Age = 5},
    new{Name = "D", Age = 3},
};
array.OrderBy(c => c.Age);
//=> {A,1} {B,1} {C,2} {D,3} {E,5}

Aggregate

全ての要素に指定された関数を実行した結果を返す

Math.Maxを使って最大値の取得
var list = new List<int>() { 1, 2, 3, 4, 5 };
list.Aggregate((current,next) => Math.Max(current,next));
//=> 5

一つの要素への処理系

Distinct

重複している要素を除外

除外
var list = new List<int>(){1,2,2,3,3,3,4,5,5};
list.Distinct();
//=> 1 2 3 4 5

二つの要素への処理系

Union

二つの要素をまとめる

まとめる
var listA = new List<int>(){1,2,3,4,5};
var listB = new List<int>(){4,5,6,7,8};
listA.Union(listB);
//=> 1 2 3 4 5 6 7 8

Intersect

二つの要素の同じ部分の抽出

同じ部分
var listA = new List<int>(){1,2,3,4,5};
var listB = new List<int>(){4,5,6,7,8};
listA.Intersect(listB);
//=> 4 5

判定系

All

全ての要素が条件を満たしているかの判定

リストの中身が全て10以下?
var list = new List<int>(){1,2,3,4,5};
list.All(c => c < 10);
//=>True

Any

条件を満たす要素が存在しているかの判定

要素==3が存在する?
var list = new List<int>(){1,2,3,4,5};
list.Any(c => c == 3);
//=>True

Contains

指定した要素が含まれているかの判定

要素1が存在する?
var list = new List<int>(){1,2,3,4,5};
list.Contains(1);
//=>True

変換系

OfType

指定した型に変換
キャストできない要素は除外される

Cast

指定した型に変換
キャストできない要素が含まれていた場合は例外スロー

ToArray

配列に変換

ToDictionary

連想配列に変換

ToList

リストに変換

4
5
0

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
4
5