开发者

Random strings using asp.net MVC3

开发者 https://www.devze.com 2023-02-28 01:20 出处:网络
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

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];
0

精彩评论

暂无评论...
验证码 换一张
取 消