码迷,mamicode.com
首页 > Windows程序 > 详细

C# 多种比较器实现

时间:2016-07-21 21:30:45      阅读:347      评论:0      收藏:0      [点我收藏+]

标签:

 C#集合实现去重,交集,差集等,用到比较时,有几种方式可以满足。

数据:

var list = new List<MyClass> {
    new MyClass {MyProperty1 = "10", MyProperty2 = "20" },
    new MyClass {MyProperty1 = "10", MyProperty2 = "30" },
    new MyClass {MyProperty1 = "20", MyProperty2 = "20" }
};

方法一:

public class MyClass
{
    public string MyProperty1 { get; set; }

    public string MyProperty2 { get; set; }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(obj, null)) return false;

        if (ReferenceEquals(this, obj)) return true;

        var o = obj as MyClass;
        return o.MyProperty1.Equals(o.MyProperty1);
    }

    public override int GetHashCode()
    {
        return MyProperty1.GetHashCode();
    }
}

用法:

list.Distinct();//去重

方法二:

public class MyClass : IEquatable<MyClass>
{
    public string MyProperty1 { get; set; }

    public string MyProperty2 { get; set; }

    public bool Equals(MyClass other)
    {
        if (ReferenceEquals(other, null)) return false;

        if (ReferenceEquals(this, other)) return true;

        return MyProperty1.Equals(other.MyProperty1);
    }
}

用法:

list.Distinct();//去重

方法三:

public class MyClass
{
    public string MyProperty1 { get; set; }

    public string MyProperty2 { get; set; }
}

public class MyClassIEqualityComparer : IEqualityComparer<MyClass>
{
    public bool Equals(MyClass x, MyClass y)
    {
        if (ReferenceEquals(x, null)) return false;
        if (ReferenceEquals(y, null)) return false;
        if (ReferenceEquals(x, y)) return true;

        return x.MyProperty1.Equals(y.MyProperty1);
    }

    public int GetHashCode(MyClass obj)
    {
        return obj.MyProperty1.GetHashCode();
    }
}

用法:

list.Distinct(new MyClassIEqualityComparer());//去重

 

C# 多种比较器实现

标签:

原文地址:http://www.cnblogs.com/quxian/p/5692887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!