An extension method on IEnumerable needed for shuffling [duplicate]

This question already has an answer here:

I need an extension method which will shuffle an IEnumerable. It can also take an int to specify the size of the returned IEnumerable. Better keeping Immutability of the IEnumerable. My current solution for IList-

public static IList Shuffle(this IList list, int size)
{
    Random rnd = new Random();
    var res = new T[size];

    res[0] = list[0];
    for (int i = 1; i < size; i++)
    {
        int j = rnd.Next(i);
        res[i] = res[j];
        res[j] = list[i];
    }
    return res;
}

public static IList Shuffle(this IList list)
{ return list.Shuffle(list.Count); }
23
задан AakashM 27 April 2011 в 16:11
поделиться