Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

c# - generate customer id using string and incremental int


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I agree with johnny 5. Basically, build the number each time you need it. The approach is going to vary highly based on how you're storing and retrieving data, i.e. locally, database, etc.

Here are some examples I whipped up.

// a basic string concantenation
private static string createIDex1(int idNum = 0)
{
    return "LCE" + idNum + "-2005";
}

// something more flexible with optional parameters and default arguments
// utilizing a single StringBUilder object is more memory efficient
private static string createIDex2(StringBuilder builder = null, int idNum = 0)
{
    // initialize fields and objects
    if (builder == null)
    {
        builder = new StringBuilder();
    }
    else
    {
        builder.Clear();
    }

    string prefix = "LCE";
    string suffix = "-2005";

    // combine
    builder.Append(prefix);
    builder.Append(idNum);
    builder.Append(suffix);

    return builder.ToString();
}

public static void Main(string[] args)
{
    StringBuilder strb = new StringBuilder();
    string custID = "";

    // some sample, auto-incrementing numbers
    // using example method 1
    for (int n = 10000; n < 10006; n++)
    {
        custID = createIDex1(n);
        Console.WriteLine(custID);
    }

    // output spacer
    Console.WriteLine();

    // using example method 2 without pasing a StringBuilder object
    for (int n = 10000; n < 10006; n++)
    {
        custID = createIDex2(null, n);
        Console.WriteLine(custID);
    }

    // output spacer
    Console.WriteLine();

    // using example method 2 while pasing a StringBuilder object
    for (int n = 10000; n < 10006; n++)
    {
        custID = createIDex2(strb, n);
        Console.WriteLine(custID);
    }

    Console.WriteLine("Press Enter key to exit");
    Console.ReadLine();
}

Output:

LCE10000-2005
LCE10001-2005
LCE10002-2005
LCE10003-2005
LCE10004-2005
LCE10005-2005

LCE10000-2005
LCE10001-2005
LCE10002-2005
LCE10003-2005
LCE10004-2005
LCE10005-2005

LCE10000-2005
LCE10001-2005
LCE10002-2005
LCE10003-2005
LCE10004-2005
LCE10005-2005
Press Enter key to exit

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...