- | rssFeed | My book on MSBuild and Team Build | Archives and Categories Wednesday, 30 July 2008

IList Randomize Extension Method

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

Visual Studio 2008 | CSharp3 Wednesday, 30 July 2008 06:31:15 (GMT Daylight Time, UTC+01:00)  #     |