- Home /
How to check if string array contains duplicates C#
Hi everyone, is there a way to tell if a string array contains duplicates of a string and remove those duplicates?
Answer by IgnoranceIsBliss · Nov 12, 2012 at 01:32 AM
This is very much a general .NET question, not a Unity specific one. For faster response you should try one of the more general forums.
Perhaps you should instead try using a List rather than an Array. These are much better for when you don't know how many elements you will have and they are much simpler to remove from.
Add 'using System.Collections.Generic' to the start of your code, then you can create a List - which is a list of strings.
It's much easier to do this work when ADDING the items to the array, rather than after they are already there.
Arrays and Lists have the function 'Contains' that you can use to check to see if it already contains a given item. If it's already there, don't add another one.
Otherwise, you'll have go through your array one element at a time, check against all of your other elements (remembering that it should ignore itself) and when you come up across a match you create a new array that is one item smaller, then copy the contents into that new array. It's not difficult to do, but using a List and removing duplicates initially is normally the much faster more efficient option.