Remove duplicates from a List in C#

前端 未结 27 1837
广开言路
广开言路 2020-11-22 04:41

Anyone have a quick method for de-duplicating a generic List in C#?

27条回答
  •  再見小時候
    2020-11-22 05:27

    Here's an extension method for removing adjacent duplicates in-situ. Call Sort() first and pass in the same IComparer. This should be more efficient than Lasse V. Karlsen's version which calls RemoveAt repeatedly (resulting in multiple block memory moves).

    public static void RemoveAdjacentDuplicates(this List List, IComparer Comparer)
    {
        int NumUnique = 0;
        for (int i = 0; i < List.Count; i++)
            if ((i == 0) || (Comparer.Compare(List[NumUnique - 1], List[i]) != 0))
                List[NumUnique++] = List[i];
        List.RemoveRange(NumUnique, List.Count - NumUnique);
    }
    

提交回复
热议问题