在 C# 中交集兩個列表


首先,設定兩個列表。

List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 };
List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 };

現在,使用 Intersect() 方法獲得兩個列表之間的交集。

IEnumerable<int> res = val1.AsQueryable().Intersect(val2);

示例

 即時演示

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

class Demo {
   static void Main() {
      List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 };
      List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 };
      IEnumerable<int> res = val1.AsQueryable().Intersect(val2);
      Console.WriteLine("Intersection of both the lists...");
      foreach (int a in res) {
         Console.WriteLine(a);
      }
   }
}

輸出

Intersection of both the lists...
40
95
110

更新日期:2020 年 6 月 22 日

8K+ 瀏覽量

開啟你的 職業生涯

透過完成課程取得認證

開始學習
廣告
© . All rights reserved.