简介
在 c# 里,比较两个 list 是否相等,需要考虑多个方面,例如列表中的元素顺序、元素本身是否相等。下面介绍几种常见的比较方法:
基本类型比较(元素顺序必须一致)
var list1 = new list<int> { 1, 2, 3 };
var list2 = new list<int> { 1, 2, 3 };
bool areequal = list1.sequenceequal(list2); // ✅ true
忽略顺序比较
var list1 = new list<int> { 1, 2, 3 };
var list2 = new list<int> { 3, 2, 1 };
bool areequal = list1.orderby(x => x).sequenceequal(list2.orderby(x => x)); // ✅ true
或先分别排完序,再比较:
list3.sort(); list4.sort(); console.writeline(list3.sequenceequal(list4)); // 输出: true
复杂类型(自定义对象列表)
- 实现
equals和gethashcode方法
public class person
{
public string name { get; set; }
public int age { get; set; }
public override bool equals(object? obj)
{
if (obj is person person)
{
return name == person.name && age == person.age;
}
return false;
}
public override int gethashcode()
{
return hashcode.combine(name, age);
}
}
使用:
console.writeline(person1.sequenceequal(person2)); // 输出: true
- 自定义比较器:
public class person
{
public string name { get; set; }
public int age { get; set; }
}
public class personcomparer : iequalitycomparer<person>
{
public bool equals(person? x, person? y)
{
return x?.name == y?.name && x?.age == y?.age;
}
public int gethashcode(person obj)
{
return hashcode.combine(obj.name, obj.age);
// 还有一种写法:
// return obj.name.gethashcode() ^ obj.age.gethashcode();
}
}
使用方式:
var list1 = new list<person>
{
new person { name = "alice", age = 25 },
new person { name = "bob", age = 30 }
};
var list2 = new list<person>
{
new person { name = "alice", age = 25 },
new person { name = "bob", age = 30 }
};
bool areequal = list1.sequenceequal(list2, new personcomparer()); // ✅ true
判断是否完全包含对方(不关心顺序)
bool setequal = list1.count == list2.count &&
!list1.except(list2).any() &&
!list2.except(list1).any();
使用 setequals(无序、无重复判断)
bool areequal = new hashset<int>(list1).setequals(list2);
或:
hashset<int> set1 = new hashset<int>(list3); hashset<int> set2 = new hashset<int>(list4); bool isequal = set1.setequals(set2); console.writeline(isequal); // 输出: true
比较两个 null 列表
list<int>? list5 = null; list<int>? list6 = null; console.writeline(list5 == list6); // 输出: true
比较两个包含null元素的列表
list<string?> list7 = new list<string?> { "a", null };
list<string?> list8 = new list<string?> { "a", null };
console.writeline(list7.sequenceequal(list8)); // 输出: true
性能优化建议
小规模数据:使用
sequenceequal或hashset。大规模数据:
- 先检查列表长度是否相同。
- 使用并行化处理(如
asparallel().sequenceequal())。
总结
| 场景 | 方法 | 是否考虑顺序 | 是否考虑重复次数 |
|---|---|---|---|
| 顺序敏感且内容相同 | sequenceequal | 是 | 是 |
| 顺序不敏感且内容相同 | hashset.setequals | 否 | 否 |
| 顺序不敏感但重复次数相同 | 排序后使用 sequenceequal | 否 | 是 |
| 自定义对象比较 | 重写 equals 或使用 iequalitycomparer | 可配置 | 可配置 |
到此这篇关于c#中比较两个list是否相等的常见方法的文章就介绍到这了,更多相关c#比较两个list相等内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论