Using List and Random

mypicturefaded 0 Tallied Votes 170 Views Share

I haven't really used Lists very much in the past so I wanted to mess around with them today and see if I could do anything that was neat.

In this snippet I create a list from a text file. In my case I used names of people I know. The program creates a list from the file using StreamReader. If the line isn't null, and isn't just whitespace it adds it to the Names List.

I then decided to try to make use of the Random class to see what it could do. I use the Random class to get a random int, with a maximum value of the number of elements in the List.

So what it does is, it pulls a name out at random. I used a while loop to draw a name at random 10 times. Just to see how random it really was. The results always varied with a relatively small sample size, so it seems to work correctly! :)

Hope you can have a little fun building on this. You could use something like this to draw names randomly for prizes at the office, or for your fantasy football team!

It does use System.Linq, which is in the 3.5 Framework, so if you don't have that, you have to replace the .ElementsAt with something else.

When the Console stops, just hit enter to continue the program.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ListTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create the list
            List<string> Names = new List<string>();

            //Open the file 
            StreamReader reader = File.OpenText(@"yourpath");
            string line;

            //Read each line in the file, and if it isn't null, and it to the List Names.
            while ((line = reader.ReadLine()) != null)
            {
                if (line.Trim() != "")
                {
                    Names.Add(line.Trim());
                }
            }
           
            //Displays each item in the List Names.
            foreach (string name in Names)
            {
                Console.WriteLine(name);
            }

            Console.ReadLine();

            int count = 0;

            //This uses the Random class to pick out an item in the List 
            //and display it to the console.
            while (count < 10)
            {
                Random number = new Random();
                int randnum = number.Next(Names.Count);

                Console.WriteLine(Names.ElementAt(randnum));
                count++;

                Console.ReadLine();
            }
        }

       
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.