I looked around for an extension method that would just randomize a list. I found a couple but they either didn't seem to work right or the modified the collection itself instead of creating a new collection and returning that. So I created one, it is pretty simple anywayz. The definition for it is shown below.
public static class IListExtensions{ public static IList<T> Randomize<T>(this IList<T> input) { if (input == null) { throw new ArgumentException("input"); }
var test = (from p in input select new { Id = rand.Next(), ListObject = p }).OrderBy(t => t.Id);
IList<T> randomList = new List<T>(); foreach (var item in test) { randomList.Add(item.ListObject); }
return randomList; }
static Random rand = new Random();}
From here we use this method just like any other IList method, an example is shown below.
public void SampleRandomize(){ int numElemnets = 10; IList<int> numList = new List<int>(); for (int i = 0; i < numElemnets; i++) { numList.Add(i); }
IList<int> radnomList = numList.Randomize();
for (int i = 0; i < randomList.Count; i++) { System.Diagnostics.Debug.WriteLine(string.Format("i: {0}", randomList[i])); }}
I think it's pretty cool how you can create methods that can be soo easily used thanks to extension methods.
Sayed Ibrahim Hashimi
Remember Me
a@href@title, b, blockquote@cite, strike, strong, sub
Theme design by Jelle Druyts
Powered by: newtelligence dasBlog 2.3.9074.18820
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010, Sayed Ibrahim Hashimi
E-mail