我需要不定时的产生一些随机数到数据库,
有什么办法保证每次运行程序产生的一批随机数都是不同的?

解决方案 »

  1.   


    int[] index = new int[15];
      for (int i = 0; i < 15; i++)
        index = i;
      Random r = new Random();
      //用来保存随机生成的不重复的10个数
      int[] result = new int[10];
      int site = 15;//设置下限
      int id;
      for (int j = 0; j < 10; j++)
      {
        id = r.Next(1, site - 1);
        //在随机位置取出一个数,保存到结果数组
        result[j] = index[id];
        //最后一个数复制到当前位置
        index[id] = index[site - 1];
        //位置的下限减少一
        site--;
      }  方法2:利用Hashtable。
      Hashtable hashtable = new Hashtable();
      Random rm = new Random();
      int RmNum = 10;
      for (int i = 0; hashtable.Count < RmNum; i++)
      {
          int nValue = rm.Next(100);
          if (!hashtable.ContainsValue(nValue) && nValue != 0)
          {
           hashtable.Add(nValue, nValue);
           Console.WriteLine(nValue.ToString());
          }
      }
      方法3:递归,用它来检测生成的随机数是否有重复,如果取出来的数字和已取得的数字有重复就重新随机获取。
      Random ra=new Random(unchecked((int)DateTime.Now.Ticks));
      int[] arrNum=new int[10];
      int tmp=0;
      int minValue=1;
      int maxValue=10;
      for (int i=0;i<10;i++)
      {
        tmp=ra.Next(minValue,maxValue); //随机取数
        arrNum=getNum(arrNum,tmp,minValue,maxValue,ra); //取出值赋到数组中
      }
      .........
      .........
      public int getNum(int[] arrNum,int tmp,int minValue,int maxValue,Random ra)
      {
        int n=0;
        while (n<=arrNum.Length-1)
        {
          if (arrNum[n]==tmp) //利用循环判断是否有重复
          {
            tmp=ra.Next(minValue,maxValue); //重新随机获取。
            getNum(arrNum,tmp,minValue,maxValue,ra);//递归:如果取出来的数字和已取得的数字有重复就重新随机获取。
          }
        n++;
        }
        return tmp;
      }
     
      

  2.   

    最简单的办法就是guid 如果你要用数字的话  那就有点小麻烦了
      

  3.   

    呃.如果一定要数字就考虑#3的.不一定纯是要求得到个不重复的就用guid吧.方便
      

  4.   

    public static Random ran = new Random();
      

  5.   


    是指一批中的每个字符都不相同吗?
    如果是的话,从 源字符串 中去掉已存在的字符,然后再调用用Random
      

  6.   

    数字的话  DateTime.Now.Ticks.ToString()+一个不重复随机的random数字
    应该也可以
    guid也可以
      

  7.   

    产生当前时间:2010080912301122
    DateTime
      

  8.   


    private static string GetRandomString(int length){
    string str = "acbdefghijklmnopqrstuvwxyzACBDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    char[] ch = new char[length];
    Random r = new Random(System.Guid.NewGuid().GetHashCode());
    for (int i = 0; i < ch.Length; i++) {
    ch[i] = str[r.Next(0,str.Length)];
    }
    return new string(ch);

    }
      

  9.   

    Guid.NewGuid() 哈哈
    泰安房产网
      

  10.   

    Guid.NewGuid() 挺好的,永远不会产生重复的
      

  11.   

    生成guid 或者 生成一个判断 再插入