Fastest way to Remove Duplicate Value from a list<> by lambda

前端 未结 7 1953
庸人自扰
庸人自扰 2020-12-01 00:55

what is fastest way to remove duplicate values from a list. Assume List longs = new List { 1, 2, 3, 4, 3, 2, 5 }; So I am interesting in

7条回答
  •  旧时难觅i
    2020-12-01 01:22

    The easiest way to get a new list would be:

    List unique = longs.Distinct().ToList();
    

    Is that good enough for you, or do you need to mutate the existing list? The latter is significantly more long-winded.

    Note that Distinct() isn't guaranteed to preserve the original order, but in the current implementation it will - and that's the most natural implementation. See my Edulinq blog post about Distinct() for more information.

    If you don't need it to be a List, you could just keep it as:

    IEnumerable unique = longs.Distinct();
    

    At this point it will go through the de-duping each time you iterate over unique though. Whether that's good or not will depend on your requirements.

提交回复
热议问题