合作联系
  wanwqing@vip.163.com
  0790-XXXXXXX
关于实验室
C#生成不重复的随机数的函数
发布者:SYS   时间:2015-10-11 20:30:26   浏览次数:179

C#生成不重复的随机数的函数.

       private ArrayList gen_rnd(int cnt, int max)
        {
            ArrayList nums = new ArrayList();//using System.Collections;
            Random rn = new Random();
            int n = 0;
            int i = 0;
            while (i < cnt)
            {
                int k = 0;
                n = rn.Next(max);

                foreach (object nn in nums)
                {
                    if (nn.ToString().Trim() == n.ToString().Trim())
                    {
                        k = 1;
                        break;
                    }
                }

                if (k == 0)
                {
                    nums.Add(n);
                    i++;
                }

            }
            return nums;
        }

=========================================

  private void button4_Click(object sender, EventArgs e)
        {
            ArrayList nums = new ArrayList();

            nums = gen_rnd(50, 100);
            listBox1.Items.Clear();
            SqlCommand mycmd;
            mycmd =mycon.CreateCommand();

            string s = "";

            for (int i = 0; i < nums.Count; i++)
            {
                s = "insert into xs_cjjd (th,zkzh) values (" + nums[i].ToString().Trim() + ",'11111111') ";
                mycmd.CommandText = s;
                mycmd.ExecuteNonQuery();

                            
                listBox1.Items.Add(nums[i].ToString());
                
            }
           }