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.
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];
精彩评论