不同的()与拉姆达? [英] Distinct() with lambda?

查看:94
本文介绍了不同的()与拉姆达?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

使用 System.Linq的,还有当然就是所谓的扩展方法鲜明。在简单的情况下,它可以在没有参数被使用,如:

  VAR distinctValues​​ = myStringList.Distinct();

当然好,但如果我有,我需要指定平等对象的枚举,唯一可用的过载是:

  VAR distinctValues​​ = myCustomerList.Distinct(someEqualityComparer);

本相等比较器参数必须是的IEqualityComparer&LT的实例; T> 。我能做到这一点,当然,但它有点冗长,那么,cludgy。

我本来期望的是,将采取一个lambda过载,说Func键< T,T,BOOL>

  VAR distinctValues
    = myCustomerList.Distinct((C1,C2)= GT; c1.CustomerId == c2.CustomerId);

任何人都知道,如果一些这样的扩展存在,或某些等效解决方法吗?还是我失去了一些东西?

另外,有指定的IEqualityComparer内联(我难堪)的一种方式?

更新

我发现由Anders Hejlsberg为一个<一个答复href=\"http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/6834054e-e1c1-49db-970c-370a9012c675\">post在关于这个问题的MSDN论坛。他说:


  

你要碰到的问题是,当两个比较对象
  等于它们必须具有相同的GetHash code返回值(或其他的
  由不同的内部使用将无法正常工作哈希表)。
  我们使用的IEqualityComparer因为它兼容包
  Equals和GetHash code的实现成一个单一的界面。


我想这是有道理的。


解决方案

 的IEnumerable&LT;客户&GT; filteredList = originalList
  .GroupBy(客户=&GT; customer.CustomerId)
  。选择(组=&GT; group.First());

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. 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<T>. 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<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?

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

Update

I found a reply by Anders Hejlsberg to a post in an MSDN forum on this subject. 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). We use IEqualityComparer because it packages compatible implementations of Equals and GetHashCode into a single interface.

I suppose that makes sense..

解决方案

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

这篇关于不同的()与拉姆达?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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