仅向DataTable添加一定百分比的行

时间:2013-05-24 20:43:19

标签: c# random datatable

所以我正在制定一个程序来随机审核我们的一些工人。我正在尝试制作一个程序来扫描我们的Access数据库并提取一定比例的订单。但我想随机选择订单,我不想只需要前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'或随机行...任何想法?

1 个答案:

答案 0 :(得分: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;
    }
}