Is there an accepted or standard way to get a unique name given a string and
the collection in which it needs to be unique? Should I use a HashTable?
Other options?
Here's a first crack:
private string makeUniqueName(string inName, MyCollection collection)
{
//if the name is not unique, append an indexer to the name
foreach (Item item in collection)
{
while (item.Text == inName)
{
string lastChar = inName.Substring(inName.Length - 1, 1);
int result;
int.TryParse(lastChar, out result);
bool lastCharIsNumeric = (result > 0 || lastChar ==
result.ToString());
result++;
if (lastCharIsNumeric)
{
inName = inName.Substring(0, inName.Length - 1);
inName = string.Concat(inName, result.ToString());
}
else
{
inName = string.Concat(inName, result.ToString());
}
}
}
string outName = inName;
//now index the name to make it unique, if it's not already unique
foreach (Item item in collection)
{
if (item.Text == outName)
{
outName = makeUniqueName(outName, collection);
}
}
return outName;
}
}