Randomise the positions of rows in a DataTable

M

Markus

Hello!

I have an DataTable with normally 5-10 records. Now I would like to display
the DataTable unsorted or randomise. When I get a Datatable with 5 Rows for
e.g., I would like to randomise the position of the rows, before I display
the Table.

Before: 1 2 3 4 5

Randomise the positions.

After: 4 2 3 5 1


How can I do this with a DataTable?

Thanks in advance!


Best Regards

Markus
 
L

Larry Smith

I have an DataTable with normally 5-10 records. Now I would like to
display the DataTable unsorted or randomise. When I get a Datatable with 5
Rows for e.g., I would like to randomise the position of the rows, before
I display the Table.

Before: 1 2 3 4 5

Randomise the positions.

After: 4 2 3 5 1


How can I do this with a DataTable?

Thanks in advance!

You can create a random sequence of numbers between zero (inclusive) and
"DataTable.Rows.Count" (exclusive). See here for a (generic) example:

http://bytes.com/groups/net-c/256178-random-number-generating

Note that in order to save memory, you may want to consider doing this
without creating an entire collection of random numbers ahead of time. Just
iterate each random number and index into "DataTable.Rows" accordingly.
You'll need to keep track of duplicates of course (so they're not reused).
Note that saving memory in your case isn't a major issue however given the
small number of records. Nevertheless, I would personally write a generic
function to iterate an arbitrary number of non-duplicate integers between
some range (pass these as arguments) and then perform an arbitrary task for
each. You can use generics to pull this this off and then stick the routine
in a reusable library.
 
M

Markus

Thank you!


Best Regards

Markus


Larry Smith said:
You can create a random sequence of numbers between zero (inclusive) and
"DataTable.Rows.Count" (exclusive). See here for a (generic) example:

http://bytes.com/groups/net-c/256178-random-number-generating

Note that in order to save memory, you may want to consider doing this
without creating an entire collection of random numbers ahead of time.
Just iterate each random number and index into "DataTable.Rows"
accordingly. You'll need to keep track of duplicates of course (so they're
not reused). Note that saving memory in your case isn't a major issue
however given the small number of records. Nevertheless, I would
personally write a generic function to iterate an arbitrary number of
non-duplicate integers between some range (pass these as arguments) and
then perform an arbitrary task for each. You can use generics to pull this
this off and then stick the routine in a reusable library.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top