Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c# - 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<T> .

(equality comparer参数必须是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>:

(我所期望的是一个需要lambda的重载,比如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)?

(或者,有没有一种方法可以指定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..

(我认为那是有道理的..)

  ask by Tor Haugen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
IEnumerable<Customer> filteredList = originalList
  .GroupBy(customer => customer.CustomerId)
  .Select(group => group.First());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...