While using linq is the best answer, here's an alternative:
string text = "1,2,3,4,4,5";
string[] parts = text.Split(',');
HashSet<string> hset = new Hashset<string>();
foreach(string item in parts)
{
hset.Add(item);
}
if (hset.Count < parts.Length)
{
}
A
HashSet
collection does not allow duplicates, but at the same time, it will not throw an exception when you try to add a duplicate.
If you want to know WHICH string(s) is/are a duplicate, you could change the code to be something like this:
string text = "1,2,3,4,4,5";
string[] parts = text.Split(',');
HashSet<string> hset = new Hashset<string>();
List<string> duplicates = new List<string>
foreach(string item in parts)
{
int oldCount = hset.Count;
hset.Add(item);
if (hset.Count == oldCount)
{
if (!duplicates.Contains(item))
{
duplicates.Add(item);
}
}
}
if (duplicates.Count > 0)
{
}
Keep in mind that the code above is case sensitive, so "Text" and "text" will be seen as different values. If that matters, and it if it won't have side effects elsewhere in your code, you can always call
ToUpper
or
ToLower
on the original
text
varaiable before processing it for duplicates.
Lastly, punctuation in a sentence can obfuscate duplicate words, so you'd probably want to remove punctuation characters from the original string, or remove them when adding them to either the
hset
and the
duplicates
collections (in the example above).