DotnetSparrow
DotnetSparrow

Reputation: 27996

Random strings using asp.net MVC3

I am creating a partial view that displays a random string on different views. How can I randomize the strings stored in arraylist or any collection and then show different news each time user requests ?

Please suggest.

Upvotes: 0

Views: 482

Answers (1)

Oded
Oded

Reputation: 499402

Use the Random class to get a random index within the list:

Random ran = new Random();
int randomIndex = ran.Next(myList.Length);

return myList[randomIndex];

Note: Since by default, Random uses time as a seed, and produces a pseudo-random result, if called in a closed loop, you can get the same string repeatedly.

I would say that since this is a web setting, and the same user will not reload that frequently, this should work fine for your purpose.


If you are calling Random often, using a static field for it can help:

// private field
private static Random ran = new Random();

// in a method
int randomIndex = ran.Next(myList.Length);

return myList[randomIndex];

Upvotes: 2

Related Questions