Linq 等式运算符:SequenceEqual

本文详细介绍了SequenceEqual方法的使用方式,包括如何检查两个列表的元素数量、值及顺序是否一致。此外,还提供了如何比较复杂类型集合的例子,并展示了实现IEqualityComparer<T>接口的方法。

检查元素的数量,每个元素的值及两个集合中元素的顺序是否相等,3个方面都相等则为true,否则为false

 

IList<string> strList1 = new List<string>(){"One", "Two", "Three", "Four", "Three"};
 
IList<string> strList2 = new List<string>(){"One", "Two", "Three", "Four", "Three"};
 
bool isEqual = strList1.SequenceEqual(strList2); // returns true

IList<string> strList1 = new List<string>(){"One", "Two", "Three", "Four", "Three"};
 
IList<string> strList2 = new List<string>(){ "Two", "One", "Three", "Four", "Three"};
 
bool isEqual = strList1.SequenceEqual(strList2); // returns false

//如果是引用类型,则比较的是引用
Student std = new Student() { StudentID = 1, StudentName = "Bill" };
 
IList<Student> studentList1 = new List<Student>(){ std };
 
IList<Student> studentList2 = new List<Student>(){ std };
        
bool isEqual = studentList1.SequenceEqual(studentList2); // returns true
 
Student std1 = new Student() { StudentID = 1, StudentName = "Bill" };
Student std2 = new Student() { StudentID = 1, StudentName = "Bill" };
 
IList<Student> studentList3 = new List<Student>(){ std1};
 
IList<Student> studentList4 = new List<Student>(){ std2 };
        
isEqual = studentList3.SequenceEqual(studentList4);// returns false

//在上面的示例中,studentList1和studentList2包含相同的学生对象std。 所以studentList1.SequenceEqual(studentList2)返回true。 但是,stdList1和stdList2包含两个独立的学生对象std1和std2。 
//所以现在,stdList1.SequenceEqual(stdList2)将返回false. //要比较复杂类型的两个集合的值,您需要实现IEqualityComperar <T>接口,如下所示
class StudentComparer : IEqualityComparer<Student> { public bool Equals(Student x, Student y) { if (x.StudentID == y.StudentID && x.StudentName.ToLower() == y.StudentName.ToLower()) return true; return false; } public int GetHashCode(Student obj) { return obj.GetHashCode(); } } // following returns true bool isEqual = studentList1.SequenceEqual(studentList2, new StudentComparer());

 

转载于:https://www.cnblogs.com/refuge/p/8151216.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值