c# list对象集合 去重

新建一个类,实现IEqualityComparer接口。注意GetHashCode方法的实现,只有HashCode相同才会去比较

    public class Compare:IEqualityComparer<Student>
    {
        public bool Equals(Student x,Student y)
        {
            return x.Id == y.Id;//可以自定义去重规则,此处将Id相同的就作为重复记录,不管学生的爱好是什么
        }
        public int GetHashCode(Student obj)
        {
            return obj.Id.GetHashCode();
        }
    }

调用:list.Distinct(new Compare()).ToList().ForEach(s => Console.WriteLine(s.ToString()));


列:
    /// <summary>
    /// list对象去重
    /// </summary>
    public class Compare : IEqualityComparer<HistoryStatisticsDTO>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool Equals(HistoryStatisticsDTO x, HistoryStatisticsDTO y)
        {
            if (x == null || y == null)
                return false;
            if (x.CaseNumId == x.CaseNumId)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int GetHashCode(HistoryStatisticsDTO obj)
        {
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return obj.CaseNumId.GetHashCode();
            } 
        }
    }

调用: var list=historyStatistics.Distinct(new Compare()).ToList();

c# list对象集合 去重

上一篇:去掉DataGridView最后一行的空白行,删除空白行


下一篇:Windows下使用ssh-add报错 Error connecting to agent: No such file or directory