Thursday, November 20, 2008

Sort Datatable randomly

4 comments
This is not possible to Sort a Datatable directly.

In order to randomize the rows in a DataTable, do the following:

1) Add a random number DataColumn to the DataTable

2) For each row, generate a random number and store it to the new column

3) Create a DataView and sort by the random number DataColumn

Test this by simple ex.

DataTable dt = GetData();
dt.Columns.Add(new DataColumn("RandomNum", Type.GetType("System.Int32")));

Random random = new Random();
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["RandNum"] = random.Next(1000);
}

DataView dv = new DataView(dt);
dv.Sort = "RandomNum";

4 comments:

LGM said...

I needed a random value in a stored procedure some time ago, and it seemed as though there was no simple solution, then while I was working with uniqueidentifiers in TSQL, I discovered that I could do a simple random number effect like this...

"Select Top 10 * from Employees order by newid();"

It works... This gives me a random selection of 10 employees...

Siva said...

Nice solution

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

LouDLeSs said...

This was exactly I was looking for. Thank you!!!