Wednesday, August 15, 2012

Ensuring a Unique Name for User Entities



        public static string GetUniqueName(string[] existingNames, string targetName)
        {
            int copyCount = 0;
 
            Regex reg = new Regex("^" + targetName + "(\\s?COPY\\s?\\d+|\\s?COPY)$");
            foreach (var name in existingNames)
            {
                if (reg.IsMatch(name))
                {
                    copyCount++;
                }
            }
            string copyName = targetName + " COPY" + (copyCount == 0 ? "" : " " + copyCount);
            return copyName;
        }


As you can see, I've hard coded COPY and the number scheme in the code above. It does a decent job of finding all names that have been previously copied and adding on another copy. Doing it this way prevents us from iterating over the existingNames collection more than once.

No comments:

Post a Comment