C# 程序打印两个列表的所有共同元素

csharpprogrammingserver side programming更新于 2025/9/20 20:30:00

首先创建两个列表 −

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

相关文章