GroupJoin()
中有一个重载方法参数包含 IEqualityComparer<Tkey>
,有没有大佬解释一下这个 IEqualityComparer
实现类的原理,想问IEqualityComparer
实现类中的Equals
方法参数x
和y
到底代表什么,下面这个例子是我的个人理解截图和官网给出的Groupjoin()
重载截图,但是对于Groupjoin()
中的IEquality
真的看不懂,和例子完全不一样,因为Equals()
中的参数x
和y
的值每次都是相等的,这样有什么比较的意义,请大佬解释一下原理,不胜感激!!!
internal 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();
}
}
internal class Program
{
private static void Main(string[] args)
{
List<Park> parks = new List<Park>(){
new Park { ticketPrice = 11, address = "天堂", peoples = 1000 },
new Park { ticketPrice = 11, address = "天堂", peoples = 1000 },
new Park { ticketPrice = 55, address = "南京", peoples = 85 },
new Park { ticketPrice = 85, address = "北京", peoples = 75 },
new Park { ticketPrice = 78, address = "多伦多", peoples = 100 },
};
//个人理解
//第一个元素默认加入distinctList的去重数组里,调用上面的Equals方法(参数x为当前元素,y为distinctList中的元素)遍历distinctList,不存在当前元素则把该元素加入distinctLsit,最后两个`address`为天堂的元素只输出一次
var diff = from c in parks.Distinct(new Park())
select c;
foreach (var item in diff)
{
Console.WriteLine(item.address);
}
😓Park不用继承IEqualityComparer<T>, 你要另外建一个类继承IEqualityComparer<T>
我知道啊,但是里面的Equanls()方法在GroupJoin里调用不太一样