Does C# Distinct() method keep original ordering of sequence intact?

Nitesh picture Nitesh · Jan 19, 2011 · Viewed 15.9k times · Source

I want to remove duplicates from list, without changing order of unique elements in the list.

Jon Skeet & others have suggested to use following

list = list.Distinct().ToList();

removing duplicates from a list C#

Remove duplicates from a List<T> in C#

Is it guaranteed that the order of unique elements would be same as before? If yes, please give a reference that confirms this as I couldn't find anything on it in documentation.

Answer

Jon Skeet picture Jon Skeet · Jan 19, 2011

It's not guaranteed, but it's the most obvious implementation. It would be hard to implement in a streaming manner (i.e. such that it returned results as soon as it could, having read as little as it could) without returning them in order.

You might want to read my blog post on the Edulinq implementation of Distinct().

Note that even if this were guaranteed for LINQ to Objects (which personally I think it should be) that wouldn't mean anything for other LINQ providers such as LINQ to SQL.

The level of guarantees provided within LINQ to Objects is a little inconsistent sometimes, IMO. Some optimizations are documented, others not. Heck, some of the documentation is flat out wrong.