Remove duplicates from a List in C#

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

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

27条回答
  •  甜味超标
    2020-11-22 05:27

    Sort it, then check two and two next to each others, as the duplicates will clump together.

    Something like this:

    list.Sort();
    Int32 index = list.Count - 1;
    while (index > 0)
    {
        if (list[index] == list[index - 1])
        {
            if (index < list.Count - 1)
                (list[index], list[list.Count - 1]) = (list[list.Count - 1], list[index]);
            list.RemoveAt(list.Count - 1);
            index--;
        }
        else
            index--;
    }
    

    Notes:

    • Comparison is done from back to front, to avoid having to resort list after each removal
    • This example now uses C# Value Tuples to do the swapping, substitute with appropriate code if you can't use that
    • The end-result is no longer sorted

提交回复
热议问题