I was in the middle of making so nice templates in order to generate some test data. I wanted to create Firstnames, Lastnames and Titles but also have them specialize by sex. So I have methods including GetMaleFirstName, GetFemaleFirstName and GetLastName. I have three xml files which have the data in and it occurred to me that I have not yet touched on LINQ to XML, so that is what I did. Of my collections I wanted to return a random element and also ensuring that whatever method I create I do not want to couple it , hence the reason I thought of an extension method for the IEnumerable<T> type. So the code is the following:
public static class Extenders
{
public static T GetSingleRandom<T>(this IEnumerable<T> target)
{
Random r = new Random(DateTime.Now.Millisecond);
int position = r.Next(target.Count<T>());
return target.ElementAt<T>(position);
}
}
You shouldn't be creating a random generator each call. Create the Random as a static property (and the default constructor would be fine).
public static class Extenders
{
public static Random r = new Random();
public static T GetSingleRandom<T>(this IEnumerable<T> target)
{
int position = r.Next(target.Count<T>());
return target.ElementAt<T>(position);
}
}
This now allows me to return a single, random, element from any IEnumerable collection. A couple of simple tests are below. The first one being on a simple list and the second on a XML File.
Example 1
//Example 1
//Simple List
IList<string> names = new List<string>();
names.Add("Andy");
names.Add("Jamie");
names.Add("John");
names.Add("David");
names.Add("Jo");
Console.WriteLine(names.GetSingleRandom<string>());
Example 2
static void Main(string[] args)
{
//Example 2
//An XML Document using LINQ to XML
string s = RandomNameAccess(@"C:\Firstnames.xml");
Console.WriteLine(s);
Console.ReadLine();
}
private static string RandomNameAccess(string fileUrl)
{
XDocument namesDocument = XDocument.Load(fileUrl);
var name = from c in namesDocument.Descendants("Names")
select c.Elements().GetSingleRandom<XElement>().Value;
return name.Single<string>();
}
I know that Visual Studio Team Edition for Database Developer has a Test Data Generator but I cannot seem to get it enabled on my version.