Amiram's answer is correct, but Distinct (), as implemented, is operation N 2 ; for each element in the list, the algorithm compares it with all elements already processed and returns it if it is unique or ignores it if not. We can do better.
A sorted list can be displayed in linear time; if the current element is equal to the previous element, ignore it, otherwise return it. Sorting is NlogN, so even for sorting the collection we get some benefit:
public static IEnumerable<T> SortAndDedupe<T>(this IEnumerable<T> input) { var toDedupe = input.OrderBy(x=>x); T prev; foreach(var element in toDedupe) { if(element == prev) continue; yield return element; prev = element; } }
This returns the same elements; they are just sorted.
KeithS Aug 08 2018-12-12T00: 00Z
source share