开发者

Does Distinct() preserve always take the first element in the list

Would

int[] nums = { 2, 3开发者_开发技巧, 3, 4, 2, 1, 6, 7, 10 };
var distinct = nums.Distinct();

always return 2, 3, 4, 1, 6, 7, 10 in that order?


The defined behavior of Enumerable.Distinct is that it will return an unordered collection (Documentation).

However the current implementation of Distinct in Linq to Objects will preserve order. This is not guaranteed for other LINQ providers though and the behavior should not be relied upon.


I think the word "unordered" means the same order of the original sequence.
Hence, the caller should decide whether to sort the result or not.


In general: no, but in your case (with an int array): probably yes. I bet they are just enumerating the collection and disregarding items they've already come across. But don't count on that behavior across different versions of .NET or for different types of collections.

As JaredPar pointed out in his answer, the result is specified as unordered. If you want some specific ordering, you need to sort them afterward using whatever algorithm makes sense in your case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜