C# Linq Except 方法


使用 Except() 方法獲取兩個陣列之間的差異。

以下是兩個陣列。

int[] arr = { 9, 12, 15, 20, 35, 40, 55, 67, 88, 92 };
int[] arr2 = { 20, 35 };

要獲取差異,請使用返回第一個列表但第二個列表中沒有元素的 Except() 方法。

arr.AsQueryable().Except(arr2);

以下是完整的示例。

示例

 即時演示

using System;
using System.Linq;
using System.Collections.Generic;
class Program {
   static void Main() {
      int[] arr = { 5, 10, 15, 20, 35, 40 };
      int[] except = { 20, 35 };
      Console.WriteLine("Initial List...");
      foreach(int ele in arr)
      Console.WriteLine(ele);
      IEnumerable<int> res = arr.AsQueryable().Except(except);
      Console.WriteLine("New List...");
      foreach (int a in res)
      Console.WriteLine(a);
   }
}

輸出

Initial List...
5
10
15
20
35
40
New List...
5
10
15
40

更新於: 23-6 月-2020

3 千 + 瀏覽量

開啟你的 職業生涯

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.