C# 比较两个List集合内容是否相同

embedded/2025/2/9 12:21:33/

 在 C# 中,要比较两个 List<T> 集合的内容是否相同,可以通过以下几种方法:

 一、非自定义类的元素比较

1. 使用 SequenceEqual 方法(顺序和内容都相等

顺序和内容都相等:使用 SequenceEqual

using System;
using System.Collections.Generic;
using System.Linq;class Program
{static void Main(){List<int> list1 = new List<int> { 1, 2, 3, 4 };List<int> list2 = new List<int> { 1, 2, 3, 4 };bool areEqual = list1.SequenceEqual(list2);Console.WriteLine($"Are the lists equal? {areEqual}");}
}

2. 自定义比较逻辑(如果顺序不重要)

忽略顺序:可以先对两个列表排序后再使用 SequenceEqual

using System;
using System.Collections.Generic;
using System.Linq;class Program
{static void Main(){List<int> list1 = new List<int> { 1, 2, 3, 4 };List<int> list2 = new List<int> { 4, 3, 2, 1 };bool areEqual = list1.OrderBy(x => x).SequenceEqual(list2.OrderBy(x => x));Console.WriteLine($"Are the lists equal (ignoring order)? {areEqual}");}
}

3. 使用 Set 比较(忽略重复元素)

忽略重复元素:可以使用 HashSet<T>

using System;
using System.Collections.Generic;class Program
{static void Main(){List<int> list1 = new List<int> { 1, 2, 3, 4 };List<int> list2 = new List<int> { 4, 3, 2, 1 };bool areEqual = new HashSet<int>(list1).SetEquals(list2);Console.WriteLine($"Are the lists equal (ignoring duplicates)? {areEqual}");}
}

 二、自定义类的元素比较

如果你想比较自定义对象的集合,比如 List<MyClass>,你需要自定义比较规则。默认情况下,List<T> 的比较是基于对象引用的比较(即两个对象的引用是否相同),而不是根据对象的内容来判断。

为了比较自定义元素,你需要重写 EqualsGetHashCode 方法。这样,比较时会依据你定义的规则进行比较。

假设你有一个自定义类 Person,你想根据 NameAge 属性来判断两个 Person 对象是否相同。

重写 EqualsGetHashCode

你需要重写 Equals 方法来比较两个对象是否相等,并且重写 GetHashCode,以确保集合操作(如 HashSetExcept)正常工作。

1、Equals 方法比较两个 Person 对象的 NameAge 属性。

 public override bool Equals(object obj){if (obj is Person other){return this.Name == other.Name && this.Age == other.Age;}return false;}

2、GetHashCode 使用 HashCode.Combine 来生成一个基于 NameAge 的哈希值,确保两个内容相同的 Person 对象具有相同的哈希值。

 public override int GetHashCode(){return HashCode.Combine(Name, Age);}

1. 顺序和内容都相等

顺序和内容都相等:使用 SequenceEqual

using System;
using System.Collections.Generic;
using System.Linq;class Person
{public string Name { get; set; }public int Age { get; set; }public override bool Equals(object obj){if (obj is Person other){return this.Name == other.Name && this.Age == other.Age;}return false;}public override int GetHashCode(){return HashCode.Combine(Name, Age);}
}class Program
{static void Main(){List<Person> list1 = new List<Person>{new Person { Name = "Alice", Age = 25 },new Person { Name = "Bob", Age = 30 }};List<Person> list2 = new List<Person>{new Person { Name = "Alice", Age = 25 },new Person { Name = "Bob", Age = 30 }};bool isSame = list1.SequenceEqual(list2);Console.WriteLine($"顺序和内容都相等: {isSame}");}
}

2. 忽略顺序

忽略顺序:先对两个列表排序,然后使用 SequenceEqual

using System;
using System.Collections.Generic;
using System.Linq;class Person
{public string Name { get; set; }public int Age { get; set; }public override bool Equals(object obj){if (obj is Person other){return this.Name == other.Name && this.Age == other.Age;}return false;}public override int GetHashCode(){return HashCode.Combine(Name, Age);}
}class Program
{static void Main(){List<Person> list1 = new List<Person>{new Person { Name = "Alice", Age = 25 },new Person { Name = "Bob", Age = 30 }};List<Person> list2 = new List<Person>{new Person { Name = "Bob", Age = 30 },new Person { Name = "Alice", Age = 25 }};bool isSame = list1.OrderBy(p => p.Name).ThenBy(p => p.Age).SequenceEqual(list2.OrderBy(p => p.Name).ThenBy(p => p.Age));Console.WriteLine($"忽略顺序: {isSame}");}
}

3. 忽略重复元素

忽略重复元素:将列表转换为 HashSet<T>,然后使用 SetEquals 方法进行比较。 

如果你希望忽略重复元素并只关心唯一元素是否相同,可以使用 HashSet<T> 来进行比较。HashSet<T> 会自动去除重复元素,因此可以通过将列表转换为 HashSet<T> 来忽略重复元素。

using System;
using System.Collections.Generic;class Person
{public string Name { get; set; }public int Age { get; set; }public override bool Equals(object obj){if (obj is Person other){return this.Name == other.Name && this.Age == other.Age;}return false;}public override int GetHashCode(){return HashCode.Combine(Name, Age);}
}class Program
{static void Main(){List<Person> list1 = new List<Person>{new Person { Name = "Alice", Age = 25 },new Person { Name = "Alice", Age = 25 },new Person { Name = "Bob", Age = 30 }};List<Person> list2 = new List<Person>{new Person { Name = "Bob", Age = 30 },new Person { Name = "Alice", Age = 25 }};bool isSame = new HashSet<Person>(list1).SetEquals(new HashSet<Person>(list2));Console.WriteLine($"忽略重复元素: {isSame}");}
}

总结

  • 顺序和内容都相等:使用 SequenceEqual
  • 忽略顺序:可以先对两个列表排序后再使用 SequenceEqual
  • 忽略重复元素:可以使用 HashSet<T>

http://www.ppmy.cn/embedded/160811.html

相关文章

go结构体和json相互转换、序列化和反序列化

json简介 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。RESTfull Api 接口中返回的数据都是 json 数据。 Json 的基本格式如下&#xff1a; { "a": "Hello", "b": "Worl…

工业 4G 路由器助力消防领域,守卫生命安全防线

在消防领域也在不断引入新技术以提升消防安全保障能力发展过程中。工业 4G 路由器为其数据传输、预警监控发挥着重要的通信作用。 工业 4G 路由器通过内置的 4G 模块&#xff0c;接入 4G 网络&#xff0c;将网络信号进行转换和分发。它能够适应复杂的工业环境&#xff0c;具备…

A new release of pip is available: 24.2 -> 25.0

您可以使用官方提供的 get-pip.py 脚本来安装或升级pip。 1&#xff0c;下载 get-pip.py 脚本&#xff1a; curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py 2&#xff0c;运行脚本以安装或升级pip&#xff1a; python get-pip.py 3&#xff0c;实际运行效果

Kotlin 2.1.0 入门教程(十)

if 表达式 if 是一个表达式&#xff0c;它会返回一个值。 不存在三元运算符&#xff08;condition ? then : else&#xff09;&#xff0c;因为 if 在这种场景下完全可以胜任。 var max aif (a < b) max bif (a > b) {max a } else {max b }max if (a > b) a…

C# 修改项目类型 应用程序程序改类库

初级代码游戏的专栏介绍与文章目录-CSDN博客 我的github&#xff1a;codetoys&#xff0c;所有代码都将会位于ctfc库中。已经放入库中我会指出在库中的位置。 这些代码大部分以Linux为目标但部分代码是纯C的&#xff0c;可以在任何平台上使用。 源码指引&#xff1a;github源…

C语言练习题

文章目录 1. 递归实现将字符串str中的元素逆序2. 对数组arr进行冒泡排序&#xff08;升序&#xff09;3. 对数组从下标low到下标hihg区间内的元素进行快速排序&#xff08;升序&#xff09;4. 在数组中利用二分查找(折半查找)目标关键字5. 求n的阶乘6. 判断year是否为闰年7. 求…

【再谈设计模式】状态模式~对象行为的状态驱动者

一、引言 在软件开发,软将工程,软件设计过程中,我们常常会遇到对象的行为依赖于其状态的情况。例如,一个任务对象可能有“未开始”、“进行中”、“已完成”等状态,并且在不同状态下执行相同操作会有不同的结果。传统的方法可能会使用大量的条件判断语句来处理不同状态下的…

申论 应用文 【2017副省第四题 “水生态+扶贫”】

材料&#xff1a; 近日&#xff0c;“秋水长天 水美中国”采访团调研了G市的水生态文明建设情况。记者经过走访发现&#xff0c;G市某些区县的“水生态扶贫”模式&#xff0c;对欠发达地区在保持青山绿水的同时大力推进脱贫工作&#xff0c;具有很强的借鉴意义。 G市以山地、…