How to extract 10 random rows from DataTable?

前端 未结 3 1957
旧巷少年郎
旧巷少年郎 2021-01-12 00:19

Let\'s say I have a DataTable with ~50 rows (GetDataTable() on a list in SharePoint). I want to keep 10 random rows and forget about the rest. How can I achieve this?

<
相关标签:
3条回答
  • 2021-01-12 00:57

    The DataTable contain a property Rows that is a DataRowCollection. You can access each of those rows by using index.

    So you can get random number with Random and get the data from the myTable.Rows[myRandomIndex].

    Random random = new Random();
    int randomNumber = random.Next(0, 50);
    
    0 讨论(0)
  • 2021-01-12 01:09

    try this:

        Random r = new Random();
        while (dt.Rows.Count > 10)
        {
            int j = r.Next(0, dt.Rows.Count);
            dt.Rows.RemoveAt(j);
        }
    
    0 讨论(0)
  • 2021-01-12 01:20

    You can use a Fisher/Yates shuffle (implementation by Skeet) on the collection of rows on the DataTable, then select the first 10.

    var random10 = dataTable.Rows.OfType<DataRow>().Shuffle(new Random()).Take(10);
    
    0 讨论(0)
提交回复
热议问题