Share and Enjoy !

I’ll spoil the fun with the extension method that makes this possible. This simply enables you to provide a list of any type, and then get a random value out of that list.

//The following defines a generic extension method which accepts an IList of type T implementation as input
public static T GetRandomItem(this IList list)
//Create an instance of Random to help get some data
Random randomizer = new Random();
//If we only have a list with one item, return the First element of type T
//I'll leave the empty set issue for the reader to solve.
if (list.Count == 1)
return list.FirstOrDefault();
//or get a 'random' element of type T between 1 and the the list count
T selectedItem = list.ElementAt(randomizer.Next(1, list.Count()));
//return our 'random' item
return selectedItem;

So how do you use this? Let’s say you have a Region class with a Name and ID property like this:

List regions = new List() {new Region() {Name="EMEA",ID =1}, new Region() {Name="AMS",ID =2}, new Region() {Name="AUS",ID =3}};

You could then get a random Region instance by calling the extension method.

Region currentRegion = regions.GetRandomItem();

This is helpful, but what if you want to load some related countries for the random Region you just obtained? If your Country has a Name and a RegionID property, this is pretty easy.

List countries = new List() {new Country() {Name="Germany",RegionID =1}, new Country() {Name="Brazil", RegionID =2}, new Country() {Name="New Zealand",RegionID =3}};

Now you can have a method which takes the input and filters the countries accoruding to the RegionID.

Region currentRegion = regions.GetRandomItem();
Country relatedCountry = countries.Where(c => c.RegionID == currentRegion.RegionID).ToList().GetRandomItem()

With these basics, using your own domain model classes, some mocks or Dependency Injection, some test values, and loading them into a SPListItem is a snap! You even get the benefit of related items and data that makes sense when you filter and sort.

Man, I love LINQ and Generics! Happy testing…

Share and Enjoy !

Related Content: