C# 中的 Union 方法


Union 方法從兩個列表中獲取唯一元素。

我們設定兩個列表 −

var list1 = new List<int>{12, 65, 88, 45};
var list2 = new List<int>{40, 34, 65};

現在讓我們求出兩個列表的並集 −

var res = list1.Union(list2);

以下為示例 −

示例

 演示

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

public class Demo {
   public static void Main() {

      // two lists
      var list1 = new List<int>{12, 65, 88, 45};
      var list2 = new List<int>{40, 34, 65};

      // finding union
      var res = list1.Union(list2);

      foreach(int i in res) {
         Console.WriteLine(i);
      }
   }
}

輸出

12
65
88
45
40
34

更新於: 2020-06-22

667 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始吧
廣告
© . All rights reserved.