Performance issue with generation of random unique numbers

前端 未结 10 628
星月不相逢
星月不相逢 2021-01-17 13:47

I have a situation where by I need to create tens of thousands of unique numbers. However these numbers must be 9 digits and cannot contain any 0\'s. My current approach is

10条回答
  •  别那么骄傲
    2021-01-17 14:19

    Something like this?

    public List generateIdentifiers2(int quantity)
            {
                var uniqueIdentifiers = new List(quantity);
                while (uniqueIdentifiers.Count < quantity)
                {
                    var sb = new StringBuilder();
                    sb.Append(random.Next(11, 100));
                    sb.Append(" ");
                    sb.Append(random.Next(11, 100));
                    sb.Append(" ");
                    sb.Append(random.Next(11, 100));
    
                    var id = sb.ToString();
                    id = new string(id.ToList().ConvertAll(x => x == '0' ? char.Parse(random.Next(1, 10).ToString()) : x).ToArray());
    
                    if (!uniqueIdentifiers.Contains(id))
                    {
                        uniqueIdentifiers.Add(id);
                    }
                }
                return uniqueIdentifiers;
            }
    

提交回复
热议问题