Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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?

like image 621
Cornelius Avatar asked Mar 19 '10 06:03

Cornelius


People also ask

Does distinct preserve order?

Java Stream distinct() MethodIf the stream is ordered, the encounter order is preserved. It means that the element occurring first will be present in the distinct elements stream.

What is distinct () in C#?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).


2 Answers

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.

like image 96
JaredPar Avatar answered Oct 21 '22 05:10

JaredPar


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.

like image 41
shahkalpesh Avatar answered Oct 21 '22 05:10

shahkalpesh