How to extract 10 random rows from a DataTable?

Say I have a DataTable with ~ 50 rows (GetDataTable () in a list in SharePoint). I want to save 10 random lines and forget about everything else. How can I achieve this?

Thanks in advance.

+6
source share
3 answers

You can use the Shuffle Fisher / Yates (Skeet implementation ) in the row collection in the DataTable, and then select the first 10.

var random10 = dataTable.Rows.OfType<DataRow>().Shuffle(new Random()).Take(10); 
+7
source

try the following:

  Random r = new Random(); while (dt.Rows.Count > 10) { int j = r.Next(0, dt.Rows.Count); dt.Rows.RemoveAt(j); } 
+1
source

The DataTable contains the Rows property, which is a DataRowCollection . You can access each of these lines using an index.

That way you can get a random number using Random and get the data from myTable.Rows[myRandomIndex] .

 Random random = new Random(); int randomNumber = random.Next(0, 50); 
0
source

Source: https://habr.com/ru/post/899506/


All Articles