views:

760

answers:

3

Hi, I am trying to make an extension method that will shuffle the contents of a generic list collection regardless of its type however im not sure what to put in between the <..> as the parameter. do i put object? or Type? I would like to be able to use this on any List collection i have.

Thanks!

public static void Shuffle(this List<???????> source)
{
    Random rnd = new Random();

    for (int i = 0; i < source.Count; i++)
    {
        int index = rnd.Next(0, source.Count);
        object o = source[0];

        source.RemoveAt(0);
        source.Insert(index, o);
    }
}
+2  A: 

You need to make it a generic method:

public static void Shuffle<T>(this List<T> source)
{
    Random rnd = new Random();

    for (int i = 0; i < source.Count; i++)
    {
        int index = rnd.Next(0, source.Count);
        T o = source[0];

        source.RemoveAt(0);
        source.Insert(index, o);
    }
}

That will allow it to work with any List<T>.

Reed Copsey
I've got to learn to type faster. Anyway, `IList<T>` would be more general.
John Saunders
when i try all the methods listed i get... Argument '2': cannot convert from 'object' to 'T'
Grant
@Grant: You need to change the portion in the middle to use "T" instead of "object" (or add a cast). As John mentioned, using IList<T> would be more general, although not all IList<T> implement insertion, so it may not work generally.
Reed Copsey
`IList<T>` has the `Insert` method. What class implements `IList<T>` and does not implement `Insert`?
John Saunders
@John: Any implementation with ICollection<T>.IsReadOnly set to true often throws on insert. I've had this bite me before. See: http://msdn.microsoft.com/en-us/library/0cfatk9t.aspx
Reed Copsey
Personally, I agree that making this work on IList<T> is better, though... its just something I thought I'd mention, as one consideration.
Reed Copsey
+3  A: 

You just make your own method generic:

public static void Shuffle<T>(this List<T> source)
Pavel Minaev
A: 

Slightly off-topic, but a Fisher-Yates shuffle will have less bias and better performance than your method:

public static void FisherYatesShuffle<T>(this IList<T> source)
{
    Random rng = new Random();

    for (int n = 0; n < source.Count; n++)
    {
        int k = rng.Next(n, source.Count);
        T tmp = source[k];
        source[k] = source[n];
        source[n] = tmp;
    }
}
LukeH