1: using System;
2: using System.Collections.Generic;
3: using System.Web;
4: using System.Web.UI;
5: using System.Web.UI.WebControls;
6:
7: public partial class randomwinner : System.Web.UI.Page
8: {
9: protected void btnSubmit_Click(object sender, EventArgs e)
10: {
11: // Get Random Winner
12: List<string> names = new List<string>();
13: names.AddRange( txtNames.Text.Split('\n') );
14:
15: // shuffle list
16: names = MixList(names);
17:
18: // Now pick a random item from the shuffled list
19: int count = names.Count;
20: Random RandomNumber = new Random();
21: int x = RandomNumber.Next(0, count-1);
22:
23: lblWinner.Text = "And the winner is: " + names[x];
24: lblWinner.Visible = true;
25: }
26:
27: private List<string> MixList(List<string> inputList)
28: {
29: List<string> randomList = new List<string>();
30: if (inputList.Count == 0)
31: return randomList;
32:
33: Random r = new Random();
34: int randomIndex = 0;
35: while (inputList.Count > 0)
36: {
37: randomIndex = r.Next(0, inputList.Count); //Choose a random object in the list
38: randomList.Add(inputList[randomIndex]); //add it to the new, random list<
39: inputList.RemoveAt(randomIndex); //remove to avoid duplicates
40: }
41:
42: //clean up
43: inputList.Clear();
44: inputList = null;
45: r = null;
46:
47: return randomList; //return the new random list
48: }
49: }