tags:

views:

86

answers:

3

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?

+5  A: 

The defined behavior of 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.

JaredPar
So it will sometimes return `{3, 2, 4, 10, 6, 7, 1}` (for example) sometimes instead of in the order in which the items was encountered? Do you perhaps have any links for this or an example code perhaps?
Cornelius
@Cornelius see my updated answer
JaredPar
A: 

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.

Isak Savo
+1  A: 

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.

shahkalpesh
You think the word "unordered" means "in a specific order"? That is a strange thing to think! :-) "Unordered" means "in no particular order".
Eric Lippert
shahkalpesh
And that order -- the order in which the original sequence appears -- is a specific order, one out of the millions of possible orders. The documentation of the method does not guarantee that this specific order is the one chosen. In *practice* this specific order is chosen. But by "unordered" the documentation means that *any order* can be chosen by the implementation. Sometimes it is more efficient to not preserve the original order.
Eric Lippert
@Eric: Thanks for your reply.
shahkalpesh