Given an array of chars, I am looking for the best way to find the first distinct char and its index in the array. This code seems to do the job, but I am wondering if there is a better way to do it without so many loops. Thanks for your input!
static string firstDistinctChar(char[] myChars)
{
string result = "No Distinct Chars found!";
Dictionary<char, int> charDict = new Dictionary<char, int>();
for (int i = 0; i < myChars.Length; i++)
{//create dictionary of char and counts of char in array
if (charDict.TryGetValue(myChars[i], out int count))
{
charDict[myChars[i]] = count + 1;
}
else
{
charDict.Add(myChars[i], 1);
}
}
foreach (var item in charDict)
{
//remove all non distinct chars from dictionary
if (item.Value > 1) { charDict.Remove(item.Key); }
}
for (int i = 0; i < myChars.Length; i++)
{
//loop thru each char in array and return first matching char and index
if (charDict.TryGetValue(myChars[i], out _))
{
result = string.Format("The char: {0} is the first distinct char in the array with an index of : {1}", myChars[i], i);
return result;
}
}
return result;
}