LINQ 学习路程 -- 查询操作 Quantifier Operators All Any Contain

OperatorDescription
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

 

posted @ 2017-03-23 00:11  蓝平凡  阅读(381)  评论(0编辑  收藏  举报