C# 自定义对象比较之绝招IEqualityComparer<T>

我们在处理对象集合的时候,难免会遇到两个对象的比较,今天给大家可以自定义的判断比较两个对象,方法就是实现IEqualityComparer。

废话不多说,程序员就是撸起袖子加油干,上代码:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;

namespace MyCode
{
    class Program
    {
        static void Main(string[] args)
        {
            var list1 = new List<Student>
            {
                new Student{Name="alice",Address="sichuang",Age=20},
                new Student{Name="bob",Address="shanghai",Age=22},
                new Student{Name="alen",Address="shanghai",Age=19}
            };

            var list2 = new List<Student>
            {
                new Student{Name="alice",Address="sichuang",Age=20}
            };
            //想去除集合list1中包含lsit2的对象
            var result1 = list1.Except(list2);//不能实现,result1集合里面依旧有alice这个对象
            var result2=list1.Except(list2, new StudentComparator());//可以实现,result2排除了alice这个对象

            Console.WriteLine($"result1:{JsonSerializer.Serialize(result1)}\n result2:{JsonSerializer.Serialize(result2)}");
        }
    }

    public class Student
    {
        public string Name { get; set; }

        public string Address { get; set; }

        public int Age { get; set; }
    }

    /// <summary>
    /// 自定义比较器
    /// </summary>
    public class StudentComparator : IEqualityComparer<Student>
    {
        public bool Equals(Student x, Student y)
        {
            return x.Name == y.Name && x.Address == y.Address && x.Age == y.Age;
        }

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

  

 

 ok,完美去除想要数据。

posted @ 2021-07-27 17:58  Miskey_Fu  阅读(465)  评论(0)    收藏  举报