在列表中查找重复项
我有以下代码:
List<MyType> myList = new List<MyType>();
// ... add items to the list
var dupes = myList.GroupBy(g => g).Where(x => (x.Count() > 1))
.Select(x => new { obj = x.Key, count = x.Count() }).ToList();
dupe
始终为空,即使我故意将重复项插入列表中也是如此。我应该在 MyType 定义中添加什么才能使其正常工作?我为 MyType 实现了 Equals(object obj)
和 CompareTo(object obj)
,但这些方法都没有被调用。
I have the following code:
List<MyType> myList = new List<MyType>();
// ... add items to the list
var dupes = myList.GroupBy(g => g).Where(x => (x.Count() > 1))
.Select(x => new { obj = x.Key, count = x.Count() }).ToList();
dupe
is always empty, even if I intentionally insert duplicates into the list. What should I add to MyType definition to make it work ? I implemented Equals(object obj)
and CompareTo(object obj)
for MyType, but none of these methods gets called.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否正确实现了 GetHashCode 以匹配您的
Equals
方法?它不会使用CompareTo
(用于排序),但将使用GetHashCode
和Equals
。如果您认为您已经完成了此操作,请发布
Equals
和GetHashCode
的代码。Have you implemented GetHashCode correctly, to match your
Equals
method? It won't be usingCompareTo
(that's for ordering) but will useGetHashCode
andEquals
.If you believe you've done that already, please post the code for
Equals
andGetHashCode
.