C# 批量随机生成不重复的礼包码

/// <summary>
/// 随机生成不重复邀请码
/// </summary>
/// <param name="length">长度</param>
/// <param name="seed">种子</param>
/// <returns></returns>

  public string CreateRandStrCode(int length, int seed = 0)
        {
            string basecode = "ABCDEFGHIJKMNPiIQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";
            //Guid的哈希码作为种子值
            byte[] buffer = Guid.NewGuid().ToByteArray();
            var ranInt = BitConverter.ToInt32(buffer, 0) + seed;

            Random random = new Random(ranInt);
            string re = "";
            for (int i = 0; i < length; i++)
            {
                int number = random.Next(basecode.Length);
                re += basecode.Substring(number, 1);
            }
            return re+ seed;
        }

        public List<string> ListCode(int max,int seed)
        {
            List<string> list = new List<string>();

            while (true)
            {
                if (list.Count == max)
                { break; }
                else
                {
                    string b = CreateRandStrCode(7, seed);
                    if (!list.Contains(b))
                    {
                        list.Add(b);
                    }
                }
            }         
            return list;
        }

//调用
  int num =0;
   List<string> listcode = ListCode(50, num++);

 

posted on 2023-01-05 09:22  嘿呀土豆  阅读(168)  评论(0编辑  收藏  举报

导航