如何使用 IEqualityComparer [英] How to use the IEqualityComparer
问题描述
我的数据库中有一些具有相同编号的铃铛.我想在没有重复的情况下获得所有这些.我创建了一个比较类来完成这项工作,但是该函数的执行会导致该函数出现很大的延迟,从 0.6 秒到 3.2 秒!
I have some bells in my database with the same number. I want to get all of them without duplication. I created a compare class to do this work, but the execution of the function causes a big delay from the function without distinct, from 0.6 sec to 3.2 sec!
我做得对还是必须使用其他方法?
Am I doing it right or do I have to use another method?
reg.AddRange(
(from a in this.dataContext.reglements
join b in this.dataContext.Clients on a.Id_client equals b.Id
where a.date_v <= datefin && a.date_v >= datedeb
where a.Id_client == b.Id
orderby a.date_v descending
select new Class_reglement
{
nom = b.Nom,
code = b.code,
Numf = a.Numf,
})
.AsEnumerable()
.Distinct(new Compare())
.ToList());
class Compare : IEqualityComparer<Class_reglement>
{
public bool Equals(Class_reglement x, Class_reglement y)
{
if (x.Numf == y.Numf)
{
return true;
}
else { return false; }
}
public int GetHashCode(Class_reglement codeh)
{
return 0;
}
}
推荐答案
您的 GetHashCode
实现始终返回相同的值.Distinct
依靠良好的哈希函数来高效工作,因为它在内部构建了一个哈希表.
Your GetHashCode
implementation always returns the same value. Distinct
relies on a good hash function to work efficiently because it internally builds a hash table.
在实现类的接口时,阅读文档,了解您应该实施哪个合同.1
在您的代码中,解决方案是将 GetHashCode
转发到 Class_reglement.Numf.GetHashCode
并在那里适当地实现它.
In your code, the solution is to forward GetHashCode
to Class_reglement.Numf.GetHashCode
and implement it appropriately there.
除此之外,您的 Equals
方法充满了不必要的代码.它可以重写如下(语义相同,代码的 1/4,更具可读性):
Apart from that, your Equals
method is full of unnecessary code. It could be rewritten as follows (same semantics, ¼ of the code, more readable):
public bool Equals(Class_reglement x, Class_reglement y)
{
return x.Numf == y.Numf;
}
最后,ToList
调用是不必要且耗时的:AddRange
接受任何 IEnumerable
因此转换为 List代码> 不是必需的.
AsEnumerable
在这里也是多余的,因为在 AddRange
中处理结果无论如何都会导致这种情况.
Lastly, the ToList
call is unnecessary and time-consuming: AddRange
accepts any IEnumerable
so conversion to a List
isn’t required. AsEnumerable
is also redundant here since processing the result in AddRange
will cause this anyway.
1在不知道实际作用的情况下编写代码被称为货物崇拜编程.这是一种令人惊讶的普遍做法.它从根本上不起作用.
1 Writing code without knowing what it actually does is called cargo cult programming. It’s a surprisingly widespread practice. It fundamentally doesn’t work.
这篇关于如何使用 IEqualityComparer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!