0

所以我正在制定一个程序来随机审计我们的一些工人。我正在尝试制作一个程序来扫描我们的 Access DB 并提取一定比例的订单。但我想随机选择订单,我不想要前 5% 什么的。

static DataTable RandomSelect(double errPercentage,string User)
    {
        OleDbConnection conn = new OleDbConnection(strAccessConn);
        string query = "SELECT ControlNumber FROM Log WHERE User ='" + User + "' AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered');";


        OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
        DataTable dt = new DataTable();
        DataTable dtRandomRows = new DataTable();

        try
        {
            adapter.Fill(dt);


            //dtRandomRows = dt.Clone();
            Random rDom = new Random();
            int i = 0;
            for (int ctr = 1; ctr <= dt.Rows.Count; ctr++)
            {
               i = rDom.Next(1, dt.Rows.Count);
               //dtRandomRows.Rows.Add(dt.Rows[i]);
                dtRandomRows.ImportRow(dt.Rows[i]);
            }
            dtRandomRows.AcceptChanges();
        }
        catch (OleDbException ex)
        {

        }

        return dtRandomRows;

    }

上面的代码可以工作,但它会从 ControlNumbers(订单)的整个表中随机选择行并将它们全部放入 dtRandomRows。但是,我只是想让它随机选择“errPercentage”或行……有什么想法吗?

4

1 回答 1

1
Random rand = new Random();

// Mark every row as not selected yet.
int[] nonSelectedRows = new int[dt.Rows.Count];
for(int i = 0; i < dt.Rows.Count; i++)
    nonSelectedRows[i] = 1;

int numSelected = 0;
int numLeft = dt.Rows.Count;
int targetNum = dt.Rows.Count * errPercentage;
while(numSelected < targetNum)
{
    for (int row = 0; row < dt.Rows.Count; row++)
    {
       // Each record has a 1/numleft chance of getting selected.
       boolean isSelected = rand.Next(numLeft) == 0; 

       // Check to make sure it hasn't already been selected.
       if(isSelected && nonSelectedRows[row] > 0)
       {
           dtRandomRows.ImportRow(dt.Rows[row]);
           nonSelectedRows[row] = -1; // Mark this row as selected.
           numSelected++;
           numLeft--;
       }

       // We've already found enough to match our targetNum.
       if(numSelected >= targetNum)
           break;
    }
}
于 2013-05-28T17:34:20.813 回答