Remove duplicates from a List in C#

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

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

27条回答
  •  情歌与酒
    2020-11-22 05:20

    David J.'s answer is a good method, no need for extra objects, sorting, etc. It can be improved on however:

    for (int innerIndex = items.Count - 1; innerIndex > outerIndex ; innerIndex--)

    So the outer loop goes top bottom for the entire list, but the inner loop goes bottom "until the outer loop position is reached".

    The outer loop makes sure the entire list is processed, the inner loop finds the actual duplicates, those can only happen in the part that the outer loop hasn't processed yet.

    Or if you don't want to do bottom up for the inner loop you could have the inner loop start at outerIndex + 1.

提交回复
热议问题