0

Sorry if the question title was a bit weird. I want to populate 500 excel rows with a composite primary key which consists of 3 columns. 2 columns automatically generate random int between 1 and 50 and third is a date between 01.01.2006 and 31.12.2013. So i want to have 500 rows, each with a different combination of the 3. Here's my code

        Type excelType = Type.GetTypeFromProgID("Excel.Application");

        dynamic excel = Activator.CreateInstance(excelType);
        excel.visible = true;

        excel.Workbooks.Add();

        Random rnd = new Random();

        dynamic sheet = excel.ActiveSheet;

        for (int i = 1; i <= 500; i++)
        {


            sheet.Cells[i, "A"] = rnd.Next(1,50);
            sheet.Cells[i, "B"] = rnd.Next(1,50);
            sheet.Cells[i, "C"] = RandomDay();

// this is where I'd check if a combination exists and if it does assign a new one

            for (int j = 0; j <= i + 1; j++)
            {
               if ( sheet.Cells[j + 1, "A"] == sheet.Cells[i, "A"] && 
                sheet.Cells[j + 1, "B"] == sheet.Cells[i, "B"] && 
                sheet.Cells[j + 1, "C"] == sheet.Cells[i, "C"])
                {
                    sheet.Cells[i, "A"] = rnd.Next(1,50);
                    sheet.Cells[i, "B"] = rnd.Next(1,50);
                    sheet.Cells[i, "C"] = RandomDay();

                }

            }

        }



    }

// random date method

    public static DateTime RandomDay()
    {
        DateTime start = new DateTime(2006, 1, 1);
        DateTime end = new DateTime(2013, 12, 31);

        Random gen = new Random();

        int range = (end - start).Days;
        return start.AddDays(gen.Next(range));
    }

I'm really not sure if this would work, plus it's running slow, it has to iterate over and over again to check if the combination exists. Does anyone have a better and faster solution? Thank you all!

4

1 回答 1

1

如果您的约束条件允许,我建议您在 excel 之外生成唯一值,然后将它们插入到 excel 中,这样您就可以将它们放入元组字典中。

这样,您可以通过从您的值创建一个字符串并将其用作字典中的键来检查预先存在的值。然后遍历您的 Dictionary 值并将它们插入到 excel 中。

HashTables(什么是字典)是查找的恒定时间,因此您将节省大量时间来保证唯一性。

Dictionary<String,Tuple<int,int,DateTime>> store = new Dictionary<String, Tuple<int, int, DateTime>>();

for (int i = 0; i < 500; i++)
{
    int n1 = rnd.Next(1,50);
    int n2 = rnd.Next(1,50);
    DateTime dt = RandomDay();

   String key = n1.ToString() + n2.ToString() + dt.ToString();

    while (store.ContainsKey(key)) {
        n1 = rnd.Next(1,50);
        n2 = rnd.Next(1,50);
        dt = RandomDay();

        key = n1.ToString() + n2.ToString() + dt.ToString();
    }

    store.Add(key, new Tuple(n1, n2, dt));
}

要添加到 excel 中,只需遍历 store.Values。

于 2013-05-19T20:43:33.763 回答