Random String of Specified Length with Enumerable


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

public static String RandomString(Int32 length)
{
 Random randomGenerator;
 String returnValue;

  randomGenerator = new Random();

  returnValue = new string(Enumerable.Range(0, length).Select(i => (char)('A' + randomGenerator.Next(0, 25))).ToArray());

 return returnValue;
}

What this does:

Enumerable.Range basically says, “Give me a collection of numbers from the first parameter to the second”, or in this case from 0 to length.

Select basically is a method that takes in an anonymous method (Lamdba expression in this case), goes through each of the items in the collection, and runs the anonymous method for every item in the collection. Not exactly sure what Select does specifically, but it is most likely something like this: (roughish psuedo code)


public static Array Select(Func func))
{

 Array returnValue;

 foreach(Int32 currentItem in Items)
 {
    returnValue.Add(func());
 }

 return returnValue;

}

Where Func is:


public Char Func()
{
 return  (char)('A' + randomGenerator.Next(0, 25);
}

Random Enumeration Generator with Generics


public static I RandomEnumeration<I>()
{
  I enumerationToCheck;
  Int32 indexToUse;
  String[] names;

  //Use activator to create an instance of the type I
  enumerationToCheck = System.Activator.CreateInstance<I>();

  //Make sure the instance is an Enumeration
   //Unfortunately you can't check that in the method 
   //delcaring using "which".
  if (enumerationToCheck as Enum == null)
  {
    throw new InvalidOperationException();
  }

  //Get the list of the enumeration item names
  names = Enum.GetNames(typeof(I));

  if (names.Length > 0)
  {
    //Grab a random name within the boundaries of the
     //names collection.
    indexToUse = RandomInt32(0, names.Length);
    //parse the name to create the random enum
    enumerationToCheck = (I)Enum.Parse(typeof(I), names[indexToUse]);
  }

  return enumerationToCheck;

}

Usage:


  SomeEnum test = RandomEnumeration();

Why bother? For unit testing and creating test classes. Possibly
for defaults on an enumeration, but not really needed since
they are value types. Oh yeah AND BECAUSE I FELT LIKE IT. I don’t
have to explain myself to you.