C# 配列同士で片方にしか存在しないデータのみを取得する

  • 作成日 2021.12.07
  • 更新日 2022.03.03
  • C#
C# 配列同士で片方にしか存在しないデータのみを取得する

C#で、配列同士で片方にしか存在しないデータのみを取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

片方にしか存在しないデータのみを取得

片方にしか存在しないデータのみを取得するには、「Except」を使用することで可能です。

int[] s1 = new int[] { 1, 2, 3, 4, 5 };
int[] s2 = new int[] { 1, 2, 3, 6 };

IEnumerable<int> s3 = s1.Except(s2); // 4,5

以下は、片方にしか存在しないデータのみを取得した結果を表示するだけのコードとなります。

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

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] s1 = new int[] { 1, 2, 3, 4, 5 };
            int[] s2 = new int[] { 1, 2, 3, 6 };
            IEnumerable<int> s3 = s1.Except(s2);

            Console.WriteLine(String.Join(", ", s3.Select(i => i)));

            // 入力待ち
            System.Console.ReadKey();
        }
    }
}

実行結果