166人参与 • 2025-04-24 • C#
在 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();
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
list<int>? list5 = null; list<int>? list6 = null; console.writeline(list5 == list6); // 输出: true
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相等内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论