IEqualityComparer的使用

当我们用Linq操作我们自定义的对像数组时,我们会发现有些方法直接使用的话根本不起作用,比如:Distinct、Except、Intersect等扩展方法。

对于我们自定义的对象的比较,我们必须实现IEqualityComparer接口来判断两个对象的相等性。

示例代码如下:

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

namespace lambda
{
    class Program
    {
        static void Main(string[] args)
        {
            Park p1 = new Park { ticketPrice = 55, address = "南京", peoples = 85 };
            Park p2 = new Park { ticketPrice = 85, address = "北京", peoples = 75 };
            Park p3 = new Park { ticketPrice = 78, address = "多伦多", peoples = 100 };
            List<Park> parks = new List<Park>(){
                new Park { ticketPrice = 11, address = "天堂", peoples = 1000 },
                new Park { ticketPrice = 11, address = "天堂", peoples = 1000 }
            };
            parks.Add(p1);
            parks.Add(p2);
            parks.Add(p3);

            var diff = from c in parks.Distinct(new Park())

                       select c;
            foreach (var item in diff)
            {
                Console.WriteLine(item.address);
            }
        }

    }

    class Park : IEqualityComparer<Park>
    {
        public double ticketPrice { get; set; }
        public string address { get; set; }
        public int peoples { get; set; }

        public bool Equals(Park x, Park y)    //比较x和y对象是否相同,按照地址比较
        {
            return x.address == y.address;
        }

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

  

或者将比较器单独写成一个类也可以,更多详细信息参见以下链接:

http://msdn.microsoft.com/zh-cn/library/ms132151.aspx

using System;
using System.Collections.Generic;
class Example
{
    static void Main()
    {
        try
        {

            BoxEqualityComparer boxEqC = new BoxEqualityComparer();

            Dictionary<Box, String> boxes = new Dictionary<Box,
                                                string>(boxEqC);

            Box redBox = new Box(4, 3, 4);
            Box blueBox = new Box(4, 3, 4);

            boxes.Add(redBox, "red");
            boxes.Add(blueBox, "blue");

            Console.WriteLine(redBox.GetHashCode());
            Console.WriteLine(blueBox.GetHashCode());
        }
        catch (ArgumentException argEx)
        {

            Console.WriteLine(argEx.Message);
        }
    }
}

public class Box
{
    public Box(int h,  int l, int w)
    {
        this.Height = h;
        this.Length = l;
        this.Width = w;
    }
    public int Height { get; set; }
    public int Length { get; set; }
    public int Width { get; set; }
}

class BoxEqualityComparer : IEqualityComparer<Box>
{

    public bool Equals(Box b1, Box b2)
    {
        if (b1.Height == b2.Height & b1.Length == b2.Length
                            & b1.Width == b2.Width)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(Box bx)
    {
        int hCode = bx.Height ^ bx.Length ^ bx.Width;
        return hCode.GetHashCode();
    }

}

  

时间: 2024-10-16 14:57:54

IEqualityComparer的使用的相关文章

Distinct&lt;TSource&gt;(IEqualityComparer&lt;TSource&gt; comparer) 根据列名来Distinct

1. DistinctEqualityComparer.cs public class DistinctEqualityComparer<T, V> : IEqualityComparer<T>     {         private Func<T, V> keySelector;         public DistinctEqualityComparer(Func<T, V> keySelector)         {             t

IEqualityComparer&lt;T&gt;接口

IEqualityComparer<T>接口的对象的主要作用在于自定义判断两个对象是否相等. 其中最常用的方法: bool Equals(T x, T y); 实现该方法用于比较两个对象是否相等.如果指定的对象相等,则为 true:否则为 false. 代码示例: class Program { static void Main(string[] args) { People p1 = new People(1, "刘备", 23); People p2 = new Peo

List Except 操作,IEqualityComparer 使用

1.此接口用于对集合 的自定义相等比较算法的实现.包含2个方法: Equals(T,T): 确定指定的对象是否相等. T 为要比较的对象类型: GetHashCode(T) :返回指定对象的哈希代码.如果两个对象的Equal 比较结果相等,则他们hashCode返回的对象也必须返回同一个值: 2. 官方建议继承 EqualityComparer<T> 而不是实现 IEqualityComparer<T> 3. Union() 这个方法将会Union(并集)两个序列(集合)连接成一个

c#List结合IEqualityComparer求交集

List元素类: public class MultiPointSearchingRet { public int ID { get; set; } public string PlateNumber { get; set; } public int VehicleBrand1 { get; set; } public string BrandName { get; set; } } 实现了IEqualityComparer的比较类: public class MultiPointSearchi

C# IEqualityComparer类型参数写法

最近在使用Union.Except时,由于默认的对比不太好使,所以需要自定义对比器,下面附上代码. class MaterialListComparer : IEqualityComparer<WonderManager.Basal.Material.Domain.Material> { public bool Equals(WonderManager.Basal.Material.Domain.Material x, WonderManager.Basal.Material.Domain.M

C#实现 Linq 序列的Distinct—— IEnumerable&lt;T&gt;.Distinct&lt;T&gt;()——IEqualityComparer

简介 在C#中使用List或者Collection的时候,我们经常需要使用到Distinct操作,但是微软默认提供的Distinct重载方法并不能满足我们的需求.这时候,我们就需要自己动手做一番工作了. Distinct方法的重载 Linq的Distinct的方法有如下一个重载版本: public static IEnumerable<TSource> Distinc<TSource>( this IEnumerable<TSource> source, IEquali

[C#.NET][VB.NET] 实践 IEqualityComparer 不分大小写

实践IEqualityComparer,不分大小写比较 //实践 public class InComparer : IEqualityComparer { CaseInsensitiveComparer myComparer = new CaseInsensitiveComparer(); public int GetHashCode(object obj) { return obj.ToString().ToLowerInvariant().GetHashCode(); } public n

C#中Dictionary的介绍

关键字:C# Dictionary 字典 作者:txw1958原文:http://www.cnblogs.com/txw1958/archive/2012/11/07/csharp-dictionary.html 说明    必须包含名空间System.Collection.Generic     Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值)     键必须是唯一的,而值不需要唯一的     键和值都可以是任何类型(比如:string, int, 自定义类型,等等

.net正则查询

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using Framework;using HraWeb.Common;using Trirand.Web.UI.WebControls;using WebApp.Common;using Contract.Domain;using