Distinct() 与 lambda?

编程入门 行业动态 更新时间:2024-10-15 20:20:59
本文介绍了Distinct() 与 lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是的,所以我有一个可枚举并希望从中获得不同的值.

Right, so I have an enumerable and wish to get distinct values from it.

使用System.Linq,当然还有一个叫做Distinct 的扩展方法.在简单的情况下,它可以不带参数使用,例如:

Using System.Linq, there's, of course, an extension method called Distinct. In the simple case, it can be used with no parameters, like:

var distinctValues = myStringList.Distinct();

很好,但是如果我有一个需要为其指定相等性的可枚举对象,则唯一可用的重载是:

Well and good, but if I have an enumerable of objects for which I need to specify equality, the only available overload is:

var distinctValues = myCustomerList.Distinct(someEqualityComparer);

相等比较器参数必须是 IEqualityComparer 的实例.我当然可以这样做,但它有点冗长,而且很笨拙.

The equality comparer argument must be an instance of IEqualityComparer<T>. I can do this, of course, but it's somewhat verbose and, well, cludgy.

我所期望的是一个使用 lambda 的重载,比如 Func:

What I would have expected is an overload that would take a lambda, say a Func<T, T, bool>:

var distinctValues = myCustomerList.Distinct((c1, c2) => c1.CustomerId == c2.CustomerId);

有谁知道是否存在一些这样的扩展,或者一些等效的解决方法?还是我遗漏了什么?

Anyone know if some such extension exists, or some equivalent workaround? Or am I missing something?

或者,有没有办法指定一个 IEqualityComparer 内联(让我难堪)?

Alternatively, is there a way of specifying an IEqualityComparer inline (embarrass me)?

更新

我找到了 Anders Hejlsberg 对 在 MSDN 论坛上发布有关此主题的信息.他说:

I found a reply by Anders Hejlsberg to a post in an MSDN forum on this subject. He says:

您将遇到的问题是当两个对象比较时等于它们必须具有相同的 GetHashCode 返回值(否则Distinct 内部使用的哈希表将无法正常运行).我们使用 IEqualityComparer 因为它包兼容将 Equals 和 GetHashCode 的实现整合到一个接口中.

The problem you're going to run into is that when two objects compare equal they must have the same GetHashCode return value (or else the hash table used internally by Distinct will not function correctly). We use IEqualityComparer because it packages compatible implementations of Equals and GetHashCode into a single interface.

我想这是有道理的.

推荐答案

IEnumerable<Customer> filteredList = originalList .GroupBy(customer => customer.CustomerId) .Select(group => group.First());

更多推荐

Distinct() 与 lambda?

本文发布于:2023-10-24 21:17:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525031.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Distinct   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!