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
{
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
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
for (int i = 0; i < numElemnets; i++)
{
numList.Add(i);
}
IList
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
Comments are closed.