I have following two approaches. Approach 1 uses a HashSet and List. Second approach uses Sorting of Array.
Which is better in terms of processing speed
- when there are many records?
- when there is small number of records?
CODE
string entryValue = "A,B, a , b, ";
if (!String.IsNullOrEmpty(entryValue.Trim()))
{
//APPROACH 1
bool isUnique = true;
//Hash set is unique set -- Case sensitivty Ignored
HashSet<string> uniqueRecipientsSet = new HashSet<string>(entryValue.Trim().Split(',').Select(t => t.Trim()),StringComparer.OrdinalIgnoreCase );
//List can hold duplicates
List<string> completeItems = new List<string>(entryValue.Trim().Split(',').Select(t => t.Trim()));
if (completeItems.Count != uniqueRecipientsSet.Count)
{
isUnique = false;
}
//APPROACH 2
bool isUniqueCheck2 = true;
string[] words = entryValue.Split(',');
Array.Sort(words);
for (int i = 1; i < words.Length; i++)
{
if (words[i].ToLower().Trim() == words[i - 1].ToLower().Trim())
{
isUniqueCheck2 = false;
break;
}
}
bool result1 = isUnique;
bool result2 = isUniqueCheck2;
}
REFERENCES:
You can simplify your first approach:
This would eliminate multiple splitting, and hide the hash set behind the call of
Distinct(). Note that theifstatement is also unnecessary.