添加for循环时添加到datagrid的重复行

问题描述 投票:-2回答:1

当我将生成的值输出到datagrid中时,它会将相同的值放入约15次,然后再将唯一值添加到datagrid中。有谁知道这个问题的解决方案或解决方法?另请注意,我在另一个for循环中运行此for循环以生成特定数量的值。

   var parts = new List<string>();
            string hash = CalculateMD5Hash(identifier);
            for (var i = 0; i < 32; i += 2)
            {
                string chars = "0123456789ABCDEFGHJKLMNPQRTUVWXY";
                var nextDigit = Convert.ToInt32(hash.Substring(i, 2), 16) & 31;
                var withDash = (((i % 8) == 0) && (i > 0));


                parts.Add(withDash ? "-" : "");
                parts.Add(chars.Substring(nextDigit, 1));




            }
            string[] array = parts.ToArray();
            string joined = string.Join("", array);

            string output = identifier + ":" + joined;
            string[] keySplit = output.Split(':');

            outputGrid.Rows.Add(keySplit[0], keySplit[1]); //Outputs mulitple times
c# for-loop datagrid
1个回答
0
投票

不要生成多个随机类,最好练习使用一个随机类,因为随机类可能具有相同的种子并生成相同的数字。这是因为它依赖于时钟来创建种子,并且在每次初始化之间可能没有很多时间的循环中,多个类将具有相同的随机种子值并产生相同的“随机”数字集,因此多次生成相同的ID。初始化一个随机类将消除此风险。

private static readonly Random generator = new Random(); 
private static readonly object syncLock = new object(); 
public static int RandomNumber(int min, int max)
{
    lock(syncLock) {
        return generator.Next(min, max); 
       }
 }

在你的GenId()方法:

string digiList = "0123456789";
string alphaList = "ABCDEFGHIJKLMNOPQRSTUVWXY";

  string id = digiList[randomNumber(0, digiList.Length)].ToString();
   id += alphaList[randomNumber(0, alphaList.Length)].ToString();
   id += alphaList[randomNumber(0, alphaList.Length)].ToString();
   id += digiList[randomNumber(0, digiList.Length)].ToString();
   id += digiList[randomNumber(0, digiList.Length)].ToString();

   return id;
© www.soinside.com 2019 - 2024. All rights reserved.