Using List and Random

mypicturefaded 0 Tallied Votes 192 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();
            }
        }

       
    }
}

Dani AI

Generated

Nice experiment, — simple, practical and a good way to learn Lists. A few small changes will make the program more reliable and easier to reuse:

  • Don't create a new Random inside the draw loop. When Random is constructed repeatedly in quick succession it can be seeded the same way and produce duplicate values. Create a single Random instance and reuse it.
  • Avoid pausing inside the loop with Console.ReadLine unless you intend to step through each pick; move the pause to the end or remove it.
  • Prefer safe file handling (dispose readers or use File.ReadLines/using) and guard for an empty file or missing path.

A concise pattern that reads, trims and returns N unique random entries (shuffle + take) looks like this:

var names = File.ReadLines(path)
    .Where(s => !string.IsNullOrWhiteSpace(s))
    .Select(s => s.Trim())
    .ToList();

var rng = new Random(); // single instance
for (int i = names.Count - 1; i > 0; i--)
{
    int j = rng.Next(i + 1);
    var tmp = names[i];
    names[i] = names[j];
    names[j] = tmp;
}

int picks = Math.Min(10, names.Count);
for (int i = 0; i < picks; i++)
    Console.WriteLine(names[i]);

Troubleshooting and enhancements: check File.Exists before reading and catch IO exceptions; if you need auditably fair draws, use a cryptographic RNG; for weighted draws keep a cumulative-weight list or expand entries according to weights; for multithreaded code use thread-local Random or a thread-safe generator. These tweaks keep the behavior deterministic, avoid accidental duplicates, and make the utility usable beyond a quick test.

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.