当前位置: 首页 > news >正文

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

 在 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.lryc.cn/news/535339.html

相关文章:

  • vue2 多页面pdf预览
  • 【python】matplotlib(animation)
  • Hello Robot 推出Stretch 3移动操作机器人,赋能研究与商业应用
  • 从零到一:我的元宵灯谜小程序诞生记
  • Docker 安装与配置 Nginx
  • Oracle常见语法
  • 在Vue3中使用Echarts的示例 两种方法
  • 【docker】docker改动镜像并重新编译举例
  • 具身智能训练新思路!将生成视频用于训练机器人
  • 15、深度学习-自学之路-反向传播程序展示、激活函数的应用,反向权重的更新、2层神经网络的应用,输入输出相关性的理解。
  • 【JavaEE进阶】依赖注入 DI详解
  • 医疗影响分割 | 使用 Swin UNETR 训练自己的数据集(3D医疗影像分割教程)
  • IGBT的两级关断
  • 微服务与网关
  • “云计算一哥”一口气发布6个大模型、3nm芯片!多模态还要搞Any-to-Any
  • pytest生成报告no tests ran in 0.01s
  • 如何修改DNS解析?
  • PyTorch 中 `torch.cuda.amp` 相关警告的解决方法
  • 微服务组件LoadBalancer负载均衡
  • 如何本地部署DeepSeek
  • vite + axios 代理不起作用 404 无效
  • centos7 升级openssl并安装python3
  • 使用 SDKMAN! 在 Mac(包括 ARM 架构的 M1/M2 芯片)上安装 Java 8
  • 【干活分享】2025年可以免费问答的一些GPT网站-deepseek等免费gpt
  • 20250211解决荣品的RK3566核心板在Android13下出现charge_extrem_low_power的问题
  • MapReduce到底是个啥?
  • 算法02-各种排序算法
  • python基础入门:8.1项目1:爬虫与数据分析
  • git 克隆指定 tag 的项目
  • DeepSeek学习笔记之——初识DeepSeek