Linq Distinct 具有单个比较类(和接口)
我的应用程序中有几个类,所有这些类都有一个 Name
属性,我想将其用作比较的基础(Distinct()
等)。由于我总是要比较 Name
,所以我决定提取一个接口 ISomeComparedStuff
,它只具有一个 Name
属性,我的所有其他类实现。我这样设置了一个比较类:
public class MyComparer : IEqualityComparer<ISomeComparedStuff>
{
public bool Equals(ISomeComparedStuff x, ISomeComparedStuff y)
{
return x.Name == y.Name;
}
public int GetHashCode(ISomeComparedStuff obj)
{
return obj.Name.GetHashCode();
}
}
唯一的问题是当我尝试针对它进行编码时:
public class SomeStuff : ISomeComparedStuff
{
...
}
public class SomeMoreStuff : ISomeComparedStuff
{
...
}
var someStuff = GetSomeStuff().Distinct(new MyComparer);
var someMoreStuff = GetSomeMoreStuff().Distinct(new MyComparer);
我收到一个强制转换错误(SomeStuff
到 ISomeComparedStuff
)。有没有办法做到这一点,这样我只需要一个比较类,否则我必须为每个类创建一个比较类(即使我总是要比较Name
)?
注意:我理解这个问题“标题”需要帮助。任何建议都会很棒。
I have several classes in my application, all of which have a Name
property that I want to use as my basis for comparison (Distinct()
, etc.). Since I am always going to be comparing on Name
, I decided to extract an interface, ISomeComparedStuff
, which simply has a Name
propery that all my other classes implement. I set up a comparison class as such:
public class MyComparer : IEqualityComparer<ISomeComparedStuff>
{
public bool Equals(ISomeComparedStuff x, ISomeComparedStuff y)
{
return x.Name == y.Name;
}
public int GetHashCode(ISomeComparedStuff obj)
{
return obj.Name.GetHashCode();
}
}
The only problem is when I try to code against it:
public class SomeStuff : ISomeComparedStuff
{
...
}
public class SomeMoreStuff : ISomeComparedStuff
{
...
}
var someStuff = GetSomeStuff().Distinct(new MyComparer);
var someMoreStuff = GetSomeMoreStuff().Distinct(new MyComparer);
I am getting a cast error (SomeStuff
to ISomeComparedStuff
). Is there some way to do this so I only need one compare class, otherwise I'd have to create one for every one of my classes (even though I am always going to compare on Name
)?
Note: I understand this question "title" needs help. Any suggestions would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定这是否是一个好的解决方案,但是让 MyComparer 成为一个泛型类怎么样?
缺点是你必须更新一个合适的版本:
扩展一点,你也可以创建一个新的扩展方法,如下所示:
Not sure if this is a good solution or not, but how about making MyComparer a generic class?
Downside is you have to new up an appropriate version:
Expanding a bit, you could also make a new extension method like this:
也许是这样的:
或者使用非通用的
IEqualityComparer
。Maybe something like:
Or use the non-generic
IEqualityComparer
.