Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract 10 random rows from DataTable?

Tags:

c#

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?

Thanks in advance.

like image 273
user997685 Avatar asked Oct 18 '11 02:10

user997685


People also ask

How do I randomly drop rows in pandas?

To remove rows at random without shuffling in Pandas DataFrame: Get an array of randomly selected row index labels. Use the drop(~) method to remove the rows.


2 Answers

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);
like image 68
tvanfosson Avatar answered Oct 24 '22 19:10

tvanfosson


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);
like image 44
Patrick Desjardins Avatar answered Oct 24 '22 19:10

Patrick Desjardins