Generating multiple random numbers

后端 未结 5 1607
时光说笑
时光说笑 2021-02-15 11:09

I want to generate 25 unique random numbers and list them in a console. The numbers should be atleast 10 characters long. Any easy way to do that?

5条回答
  •  醉梦人生
    2021-02-15 11:51

    Try building the numbers up as strings, and use a HashSet to ensure they are unique:

    Random random = new Random();
    HashSet ids = new HashSet();
    
    while (ids.Count < 25)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 10; ++i)
        {
            sb.Append(random.Next(10));
        }
        ids.Add(sb.ToString());
    }
    

    Example output:

    7895499338
    2643703497
    0126762624
    8623017810
    ...etc...
    

    The class HashSet is present in .NET 3.5 and newer.

提交回复
热议问题