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
710 views
in Technique[技术] by (71.8m points)

.net - How to generate a random 10 digit number in C#?

I'm using C# and I need to generate a random 10 digit number. So far, I've only had luck finding examples indicating min maximum value. How would i go about generating a random number that is 10 digits, which can begin with 0, (initially, I was hoping for random.Next(1000000000,9999999999) but I doubt this is what I want).

My code looks like this right now:

[WebMethod]
public string GenerateNumber()
{
    Random random = new Random();
    return random.Next(?);
}

**Update ended up doing like so,

[WebMethod]
public string GenerateNumber()
{
    Random random = new Random();
    string r = "";
    int i;
    for (i = 1; i < 11; i++)
    {
        r += random.Next(0, 9).ToString();
    }
    return r;
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use this to create random digits with any specified length

public string RandomDigits(int length)
{
    var random = new Random();
    string s = string.Empty;
    for (int i = 0; i < length; i++)
        s = String.Concat(s, random.Next(10).ToString());
    return s;
}

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

...