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

后端 未结 6 821
情话喂你
情话喂你 2020-11-29 11:01

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

Jon Skeet & others have suggested to use following

         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 11:33

    Yes, Enumerable.Distinct preserves order. Assuming the method to be lazy "yields distinct values are soon as they are seen", it follows automatically. Think about it.

    The .NET Reference source confirms. It returns a subsequence, the first element in each equivalence class.

    foreach (TSource element in source)
        if (set.Add(element)) yield return element;
    

    The .NET Core implementation is similar.

    Frustratingly, the documentation for Enumerable.Distinct is confused on this point:

    The result sequence is unordered.

    I can only imagine they mean "the result sequence is not sorted." You could implement Distinct by presorting then comparing each element to the previous, but this would not be lazy as defined above.

提交回复
热议问题