Fun Coding

学んだことを記録していきます!

【C#】リストに特定の要素が含まれているか判断する方法 まとめ

リストに特定の要素が含まれているか判断するメソッドは3つあります。

方法
メソッド名
Contains
Exists
Any
共通の仕様

・特定の要素が含まれている場合はTrueを返す
・特定の要素が含まれていない場合はFalseを返す

異なる仕様
方法
メソッド名
引数
引数がない場合
Contains オブジェクト ビルドエラーとなる
Exists 条件 ビルドエラーとなる
Any 条件 要素が存在するか判断する

コード
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sample {
    /// <summary>
    /// メインプログラム
    /// </summary>
    public class Program {
        /// <summary>
        /// 方法の比較
        /// </summary>
        static void Main() {
            // リストを生成
            var list = new List<string>();

            // リストに値を追加
            list.Add("A");
            list.Add("BB");
            list.Add("CCC");

            // Aが存在するか確認
            bool result1 = list.Contains("A");
            bool result2 = list.Exists(n => n == "A");
            bool result3 = list.Any(n => n == "A");

            Console.WriteLine("Aが存在する");
            Console.WriteLine("Contains : " + result1);
            Console.WriteLine("Exists : " + result2);
            Console.WriteLine("Any : " + result3);
            Console.WriteLine();


            // Dが存在するか確認
            result1 = list.Contains("D");
            result2 = list.Exists(n => n == "D");
            result3 = list.Any(n => n == "D");

            Console.WriteLine("Dが存在する");
            Console.WriteLine("Contains : " + result1);
            Console.WriteLine("Exists : " + result2);
            Console.WriteLine("Any : " + result3);
            Console.WriteLine();


            // 長さが3の要素が存在するか確認
            /* result1 = list.Contains(n => n.Length == 3); */
            result2 = list.Exists(n => n.Length == 3);
            result3 = list.Any(n => n.Length == 3);

            Console.WriteLine("長さが3の要素が存在する");
            Console.WriteLine("Contains : ビルドエラー");
            Console.WriteLine("Exists : " + result2);
            Console.WriteLine("Any : " + result3);
            Console.WriteLine();


            // 要素が存在するか確認
            /* result1 = list.Contains(); */
            /* result2 = list.Exists(); */
            result3 = list.Any();

            Console.WriteLine("要素が存在する");
            Console.WriteLine("Contains : ビルドエラー");
            Console.WriteLine("Exists : ビルドエラー");
            Console.WriteLine("Any : " + result3);
            Console.WriteLine();
        }
    }
}
出力
Aが存在する
Contains : True
Exists : True
Any : True

Dが存在する
Contains : False
Exists : False
Any : False

長さが3の要素が存在する
Contains : ビルドエラー
Exists : True
Any : True

要素が存在する
Contains : ビルドエラー
Exists : ビルドエラー
Any : True