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);
}