C# 程式來列印兩個列表中的所有公共元素


首先建立兩個列表 -

List list1 = new List() {40, 20, 60, 3, 55};
List list2 = new List() {20, 70, 55, 80};

要查詢公共元素,請使用 Intersect -

list1.Intersect(list2)

以下是查詢兩個列表之間公共元素的完整程式碼 -

示例

 現場演示

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

namespace Demo {
   class Program {
      static void Main(string[] args) {
         List list1 = new List() {40, 20, 60, 3, 55};
         List list2 = new List() {20, 70, 55, 80};
         Console.WriteLine("Common elements:");
         foreach(int value in list1.Intersect(list2))
         Console.WriteLine(value);
      }
   }
}

輸出

Common elements:
20
55

更新於: 20-Jun-2020

2K+ 檢視

開啟你的 職業

完成課程以獲得認證

現在開始
廣告