How to generate random unique 16 digit number in asp.net without collision

大兔子大兔子 提交于 2019-11-30 15:39:27

You can create a random number using the Random class:

private static Random RNG = new Random();

public string Create16DigitString()
{
  var builder = new StringBuilder();
  while (builder.Length < 16) 
  {
    builder.Append(RNG.Next(10).ToString());
  }
  return builder.ToString();
}

Ensuring that there are no collisions requires you to track all results that you have previously returned, which is in effect a memory leak (NB I do not recommend that you use this - keeping track of all previous results is a bad idea, rely on the entropy of a random string of up to 16 characters, if you want more uniqueness, increase the entropy, but I shall include it to show how it could be done):

private static HashSet<string> Results = new HashSet<string>();

public string CreateUnique16DigitString()
{
  var result = Create16DigitString();
  while (!Results.Add(result))
  {
    result = Create16DigitString();
  }

  return result;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!