LINQ 学习路程 -- 查询操作 Quantifier Operators All Any Contain
Posted 蓝平凡
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LINQ 学习路程 -- 查询操作 Quantifier Operators All Any Contain相关的知识,希望对你有一定的参考价值。
Operator | Description |
---|---|
All | 判断所有的元素是否满足条件 |
Any | 判断存在一个元素满足条件 |
Contain | 判断是否包含元素 |
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18 } , new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 } }; // checks whether all the students are teenagers bool areAllStudentsTeenAger = studentList.All(s => s.Age > 12 && s.Age < 20); Console.WriteLine(areAllStudentsTeenAger);
bool isAnyStudentTeenAger = studentList.Any(s => s.age > 12 && s.age < 20);
Contains
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value); public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer);
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18 } , new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 } }; Student std = new Student(){ StudentID =3, StudentName = "Bill"}; bool result = studentList.Contains(std); //returns false
上面的result将是false,即使“”Bill"在集合中,因为Contains仅仅比较对象的引用,而不是对象的值。所以要比较对象的值,需要实现IEqualityComparer接口
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(); } }
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18 } , new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 } }; Student std = new Student(){ StudentID =3, StudentName = "Bill"}; bool result = studentList.Contains(std, new StudentComparer()); //returns true
以上是关于LINQ 学习路程 -- 查询操作 Quantifier Operators All Any Contain的主要内容,如果未能解决你的问题,请参考以下文章
LINQ 学习路程 -- 查询操作 GroupBy ToLookUp
LINQ 学习路程 -- 查询操作 OrderBy & OrderByDescending