コレクション

[C#] 要素のいずれかが条件に合致しているか判定する(.Any)

2021年7月17日

コレクション要素のいずれかが条件に合致しているか判定するには、.Any() を使用します。

サンプル

例1)List型の場合

using System.Collections.Generic;
using System.Linq;

//intのListを生成
List<int> list = new List<int>(){7, 3, 9, 3, 5, 3};

//要素に9が存在しているか判定する
bool b = list.Any(x => x == 9);

結果

true

例2)Dictionary型の場合

using System.Collections.Generic;
using System.Linq;

//Dictioinaryの生成
Dictionary<string, string> dc = new Dictionary<string, string>();
dc.Add("01", "大阪");
dc.Add("02", "京都");
dc.Add("03", "神戸");

//Key="03"が存在するか判定する
bool b = dc.Any(x => x.Key == "03");

結果

true

例3)データクラスListの場合

using System.Collections.Generic;
using System.Linq;

//データクラス(Prefクラス)
class Pref{
  public int No {get; set;}
  public string Name {get; set;}
  public int Population {get; set;}
}

//PrefのListを生成
var list = new List<Pref>();
list.Add(new Pref{No=1, Name="北海道", Population=5381733});
list.Add(new Pref{No=2, Name="青森県", Population=1308265});
list.Add(new Pref{No=3, Name="岩手県", Population=1279594});
list.Add(new Pref{No=2, Name="青森県", Population=1308265});
list.Add(new Pref{No=3, Name="岩手県", Population=1279594});

//Pref.Populationが600万以上の要素が存在するか判定する
bool b = list.Any(x => x.Population >= 6000000);

結果

false

備考

  • LINQを使用するには、「using System.Linq;」の宣言が必要です。
  • コレクション要素であれば、List型でもDictionary型でも使用できます。

-コレクション
-, ,