java lambada distint_Distinct()与lambda? - Distinct() with lambda?

问题:

Right, so I have an enumerable and wish to get distinct values from it. 是的,所以我有一个可枚举的,并希望从中获得不同的值。

Using System.Linq , there's of course an extension method called Distinct . 使用System.Linq ,当然有一个名为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);

The equality comparer argument must be an instance of IEqualityComparer . equality comparer参数必须是IEqualityComparer的实例。 I can do this, of course, but it's somewhat verbose and, well, cludgy. 当然,我可以做到这一点,但它有点冗长,而且很有说服力。

What I would have expected is an overload that would take a lambda, say a Func: 我所期望的是一个需要lambda的重载,比如Func :

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? 或者我错过了什么?

Alternatively, is there a way of specifying an IEqualityComparer inline (embarass me)? 或者,有没有一种方法可以指定IEqualityComparer内联(embarass me)?

Update 更新

I found a reply by Anders Hejlsberg to a post in an MSDN forum on this subject. 我找到了Anders Hejlsberg对MSDN论坛中关于这个主题的帖子的回复。 He says: 他说:

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). 您将要遇到的问题是,当两个对象比较相等时,它们必须具有相同的GetHashCode返回值(否则Distinct内部使用的哈希表将无法正常运行)。 We use IEqualityComparer because it packages compatible implementations of Equals and GetHashCode into a single interface. 我们使用IEqualityComparer,因为它将Equals和GetHashCode的兼容实现打包到一个接口中。

I suppose that makes sense.. 我认为那是有道理的..

解决方案:参考一:

https://stackoom.com/question/5SDA/Distinct-与lambda

参考二:

https://oldbug.net/q/5SDA/Distinct-with-lambda

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值