如何在 C# 中对两个列表进行比较,并将差值加到第三个列表中?
首先,设置这两个列表 −
列表一
List < string > list1 = new List < string > ();
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");列表二
List < string > list2 = new List < string > ();
list2.Add("C");
list2.Add("D");找出两个列表的差值并显示不同的元素 −
IEnumerable < string > list3;
list3 = list1.Except(list2);
foreach(string value in list3) {
Console.WriteLine(value);
}以下是比较两个列表的完整示例 −
示例
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
List < string > list1 = new List < string > ();
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");
Console.WriteLine("First list...");
foreach(string value in list1) {
Console.WriteLine(value);
}
Console.WriteLine("Second list...");
List < string > list2 = new List < string > ();
list2.Add("C");
list2.Add("D");
foreach(string value in list2) {
Console.WriteLine(value);
}
Console.WriteLine("Difference in the two lists...");
IEnumerable < string > list3;
list3 = list1.Except(list2);
foreach(string value in list3) {
Console.WriteLine(value);
}
}
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP