Distinct() 与 lambda? [英] Distinct() with lambda?

查看:32
本文介绍了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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆