- Home /
How do I scan a list and remove all duplicates
I have this list that at the start of the game it gathers up all the objects with a given tag. What I want to do is after it collects all the objects with that tag I want it to go through and remove all duplicates. How can I do this?
What type of list? Built-in array? List<T>
? Does it matter if other elements are re-arranged during the process(I.e. is it unordered)?
Answer by Statement · Aug 10, 2011 at 01:44 PM
Add `using System.Linq;` to your using declarations.
If you want to do it easily with Linq method Distinct:
// C# (.cs)
yourList = yourList.Distinct().ToList();
You can do it in UnityScript as well, but as far as I know (unless 3.4 changed this) you have to call the static functions yourself, and I think this is how it is done...
// UnityScript/JavaScript (.js)
yourList = Enumerable.ToList(Enumerable.Distinct(yourList));
Answer by jeryymanly · Oct 07, 2016 at 07:43 AM
Get duplicate items from a list using LINQ
List duplicates = lst.GroupBy(x => x) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToList();
More about...C# List
Jeryy