Remove duplicates from a List in C#

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

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

27条回答
  •  [愿得一人]
    2020-11-22 05:12

    Use Linq's Union method.

    Note: This solution requires no knowledge of Linq, aside from that it exists.

    Code

    Begin by adding the following to the top of your class file:

    using System.Linq;
    

    Now, you can use the following to remove duplicates from an object called, obj1:

    obj1 = obj1.Union(obj1).ToList();
    

    Note: Rename obj1 to the name of your object.

    How it works

    1. The Union command lists one of each entry of two source objects. Since obj1 is both source objects, this reduces obj1 to one of each entry.

    2. The ToList() returns a new List. This is necessary, because Linq commands like Union returns the result as an IEnumerable result instead of modifying the original List or returning a new List.

提交回复
热议问题