Generate randomized data from a list of values in .NET

Posted by Max | Posted in programming | Posted on 17-12-2009

0

Sometimes you need to generate some test data for demo purspses. Randomizer class allows you to do it easily.


/// <summary>
    /// Gets a random value from list
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Randomizer<T> : List<T>
    {
        private static readonly Random Random = new Random();

        public T GetValue()
        {
            return this[Random.Next(Count)];
        }

        public List<T> GetValues(int listSize)
        {
            var result = new List<T>();
            for(var i=0; i<listSize; i++)
                result.Add(GetValue());
            return result;
        }
    }

    class Program
    {
        static void Main()
        {
            // init list of values
            var firstNames = new Randomizer<string> { "Peter", "Paul", "Jane", "Irene", "Michael", "Sara" };
            var lastNames = new Randomizer<string> { "Smith", "Doe", "Jackson" };
            var dates = new Randomizer<DateTime> { new DateTime(2009,1,1), DateTime.Now, DateTime.Now.AddDays(2) };

            // get list of 20 random order values from list of names
            firstNames.GetValues(20).ForEach(x => Console.Write("{0}\n", x));

            // generate details for 10 users
            for(var i=0; i<10; i++)
                Console.Write("User: {0} {1} Born: {2}\n", firstNames.GetValue(), lastNames.GetValue(), dates.GetValue());
        }
    }

Write a comment