Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

How can I select a random row when running through a foreach loop of DataRows.

Thanks so much for the help.
RB
Posted

Try reading a bit. Google is your friend

1,640,000 results... Try something. If you have issues at that point, ask something more specific. (i.e. Make an effort, please)
 
Share this answer
 
v2
Comments
Nish Nishant 1-Feb-11 14:29pm    
Ah, I thought by "random" he meant "an arbitrary" row.
fjdiewornncalwe 1-Feb-11 14:43pm    
You're probably right, but I put this answer because the OP hasn't demonstrated any effort towards his solution as far as we can see. It was my not so subtle way of pulling more information out of him. :) (Your answer is very good, however, and if the OP turns out to be looking for the arbitrary answer you provide, you'll get the +5 from me.)
Nish Nishant 1-Feb-11 14:45pm    
Yeah this is kinda like a mind game, where you try to guess what the OP really wants :-)
Sergey Alexandrovich Kryukov 2-Feb-11 20:09pm    
I see two different understandings of the word "random".
Who cares? this OP's business.
Mine is to vote 5.
--SA
Assume you have a table called tbl that has been filled and has rows:
C#
Random rndm = new Random();
DataRow rndm_row;

foreach(DataRow row in tbl.Rows)
{

     rndm_row = tbl.Rows[rndm.Next(0,tbl.Rows.Count - 1)];

     // Do something with rndm_row

}

Out of curiousity, why would you want to do that?
 
Share this answer
 
Comments
RadioButton 1-Feb-11 15:18pm    
Thank for the answer. I had not thought have that. Very simple. The reason why I want to do this is to select from a random set of auto responses stored in the db.
JOAT-MON 1-Feb-11 15:44pm    
Oh, okay...what you really need is just the Random class, not the foreach loop. Foreach is just for doing an iterated walk of collections.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900