Linq 对象的比较 Contains,Max

 

Contains

    public class StudentEquality : IEqualityComparer<Student>
    {

        public static StudentEquality Instance { get; set; }

        private StudentEquality()
        {

        }

        static StudentEquality()
        {
            Instance = new StudentEquality();
        }


        public bool Equals(Student x, Student y)
        {
            if (x == null || y == null)
            {
                return false;
            }

            if (x.StudentID == y.StudentID)
            {
                return true;
            }

            return false;
        }

        public int GetHashCode(Student obj)
        {
            return obj.GetHashCode();
        }
    }

 

            List<Student> studentList = new List<Student>() {
                new Student() { StudentID = 1, StudentName = "Zohn", StandardID =1 },
                new Student() { StudentID = 2, StudentName = "Moin", StandardID =1 },
                new Student() { StudentID = 3, StudentName = "Bill", StandardID =2 },
                new Student() { StudentID = 4, StudentName = "Ram1" , StandardID =2 },
                new Student() { StudentID = 5, StudentName = "Ron1123", StandardID = 3  }
            };

            Student s = new Student() { StudentID = 5, StudentName = "Ron1123", StandardID = 3 };
            bool res = studentList.Contains(s, StudentEquality.Instance);
            Console.WriteLine("Contains = " + res);// True

 

 

 

Max

    public class StudentComparable : IComparable<StudentComparable>
    {
        public Student Student { get; set; }

        public int CompareTo(StudentComparable other)
        {
            if (Student.StudentName.Length > other.Student.StudentName.Length)
            {
                return 1;
            }

            if (Student.StudentName.Length == other.Student.StudentName.Length)
            {
                return 0;
            }
            return -1;
        }
    }

 

            IList<Student> studentList = new List<Student>() {
                new Student() { StudentID = 1, StudentName = "Zohn", StandardID =1 },
                new Student() { StudentID = 2, StudentName = "Moin", StandardID =1 },
                new Student() { StudentID = 3, StudentName = "Bill", StandardID =2 },
                new Student() { StudentID = 4, StudentName = "Ram1" , StandardID =2 },
                new Student() { StudentID = 5, StudentName = "Ron1123", StandardID = 3  }
            };
            //选出最长的名字的 Student
            StudentComparable max = studentList.Max(m => new StudentComparable { Student = m });
            Console.WriteLine(JsonConvert.SerializeObject(max.Student));
            Console.Read();

 

posted @ 2017-12-30 18:14  热敷哥  阅读(214)  评论(0编辑  收藏  举报