Anyone have a quick method for de-duplicating a generic List in C#?
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
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.
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.