The basic idea is not to allow the same texts and add +1 at the end.
Imagine that I have a datagrid (wpf) with names, and every time I click the add button, I will put a new name on the list automatically by running this method to ensure that no two names alike. My standard used: if repeated text, add to the end "(" + count + ")", similar to windows explorer.
Ways to make using LINQ? or Regex?
private void Test()
{
var result = CreateText("t", new string[] { "t", "t(1)", "t(2)", "t(3)", "t(4)", "t(5)", "t(6)", "t(7)", "t(8)", "t(9)", "t(10)" });
Assert.IsTrue(result == "t(11)");
}
public static String CreateText(string newText, String[] texts)
{
int addCount = 0;
foreach (String text in texts)
{
if (text.IndexOf(newText) == 0)
{
if (text == newText && addCount == 0)
{
addCount = 1;
continue;
}
else
{
if (text.LastIndexOf('(') == newText.Length && text.LastIndexOf(')') == text.Length - 1)
{
try
{
var initial = text.LastIndexOf('(') + 1;
var size = text.LastIndexOf(')') - initial;
int count = Int16.Parse(text.Substring(initial, size));
if (addCount <= count)
{
addCount = count + 1;
}
}
catch (Exception)
{
addCount = 0;
}
}
}
}
}
if (addCount > 0)
{
newText += "(" + addCount + ")";
}
return newText;
}