0

This is the example for the usage of Distinct from https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinct

List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };

IEnumerable<int> distinctAges = ages.Distinct();

Console.WriteLine("Distinct ages:");

foreach (int age in distinctAges)
{
    Console.WriteLine(age);
}

/*
 This code produces the following output:

 Distinct ages:
 21
 46
 55
 17
*/

The algorithm seems to be very simple: Iterate the elements. If the current element is unknown, copy it to the result, otherwise discard it.

I want to know if all implementations are required to give this result, or could a future implementation as well output 55, 21, 17, 46?

htho
  • 1,549
  • 1
  • 12
  • 33
  • 2
    While it's not guaranteed to keep the same order I highly doubt the implementation would ever change to result in a different order. – juharr Dec 15 '20 at 13:29

2 Answers2

2

From your link:

Remarks

The result sequence is unordered.

and later:

The Distinct<TSource>(IEnumerable<TSource>) method returns an unordered sequence that contains no duplicate values

canton7
  • 37,633
  • 3
  • 64
  • 77
  • Of course I read the docs. But there is a certain ambiguity in the formulation. Let's test the formulation by inverting it: An "ordered" sequence would imply that some sort algorithm was applied to the Enumerable. This is not the case, therefore it is "unordered". Therefore "unordered" does not say anything about the (lets call it) "stability" of the result. – htho Dec 15 '20 at 15:32
  • 1
    "Unordered sequence" means that no guarantees are made about the order of the sequence. – canton7 Dec 15 '20 at 15:35
0

Seems like it always give them back in the order you put them. I tried and these are the results:

IEnumerable pippo = new List { 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 1, 4, 3, 5, 2, 1, 2, 3, 5, 4, 2, 3, 4, 5, 1, 3, 5, 6, 7 };

pippo.Distinct() Distinct

Iterator { 1, 2, 3, 4, 5, 6, 7 }

pippo.Distinct() Distinct

Iterator { 1, 2, 3, 4, 5, 6, 7 }

pippo.Distinct() Distinct

Iterator { 1, 2, 3, 4, 5, 6, 7 }

IEnumerable pippo = new List { 99, 12, 33 ,1,2,3,4,5,6,7,8,11,33,44,1,2,3,4,5,6,7,99};

pippo.Distinct() Distinct

Iterator { 99, 12, 33, 1, 2, 3, 4, 5, 6, 7, 8, 11, 44 }

pippo.Distinct() Distinct

Iterator { 99, 12, 33, 1, 2, 3, 4, 5, 6, 7, 8, 11, 44 }

pippo.Distinct() Distinct

Iterator { 99, 12, 33, 1, 2, 3, 4, 5, 6, 7, 8, 11, 44 }

Even in different executions and instances I got the same result.

Liquid Core
  • 1
  • 6
  • 27
  • 52
  • 3
    The [current implementation works this way](https://source.dot.net/#System.Linq/System/Linq/Distinct.cs,43) (it's easier to see from the source, rather than testing), but while it's very unlikely to change, that's not guaranteed by the documentation – canton7 Dec 15 '20 at 13:58