Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

IEnumerable.Exceptメソッド

Enumerable.Except(TSource) メソッド (IEnumerable(TSource), IEnumerable(TSource)) (System.Linq)
既定の等値比較子を使用して値を比較することにより、2 つのシーケンスの差集合を生成します。

SQLでは、WHERE〜NOT IN〜に相当します。

ソースコード

using System;
using System.Linq;

namespace LinqSample {
    class Program {
        static void Main(string[] args) {
            int[] numbers1 = new int[] { 1, 2, 3, 4, 5 };
            int[] numbers2 = new int[] { 1, 2, 3 };
            // 4, 5
            Console.WriteLine(numbers1.Except(numbers2).Sum());
            // なし
            Console.WriteLine(numbers2.Except(numbers1).Sum());
            Console.ReadKey();
        }
    }
}

実行結果