在保存c#和sql server之前找到唯一的名称

时间:2013-10-22 15:04:02

标签: unique handle names

我必须处理唯一的名称并将其保存在db中 -

如果名称已存在,请找到您可以附加到名称的最小数字,以将其另存为唯一名称。

例如:     如果用户名Scott已存在,请另存为Scott(1)。如果Scott(1)已经存在,请保存为Scott(2)。等

我正在使用c#和sql server 2010

任何好主意?

1 个答案:

答案 0 :(得分:0)

想出来 - 但欣赏改进

            var seprator = "scott";

        var list = new List<string>();

        list.Add("scott");
        list.Add("scott(1)");
        list.Add("scott Alex");
        list.Add("scott (4)");
        list.Add("scott(xxx)");
        list.Add("scott(250)");
        list.Add("scott(12s)");
        list.Add("scott(123)x");
        list.Add("Scott caps");
        list.Add("Alex Scott caps");
        list.Add("xxxscottmmm");


        var numberList = new List<int>();

        foreach (var v in list)
        {
            var parts = Regex.Split(v, seprator, RegexOptions.IgnoreCase);

            if (parts.Length > 1)  //(1) Alex (4) (xxx) (250) (12s) (123)x caps caps 
            {
                var secondPart = parts[1].Trim();

                if (secondPart.StartsWith("(") && secondPart.EndsWith(")"))  // (1) (4) (xxx) (250) (12s)
                {
                    var valuebetweenbraces = secondPart.Substring(1, secondPart.Length - 2);  //1 4 xxx 250 12s 

                    int number;
                    var isNumber = int.TryParse(valuebetweenbraces, out number);

                    if (isNumber)
                    {
                        numberList.Add(number);
                    }
                }
            }
        }

        int maxValue = 0;

                    if (numberList.Count > 0)
                        maxValue = numberList.Max() + 1;
                    else
                        maxValue = maxValue + 1;
                       Response.Write(seprator + "(" + maxValue  + ")");