Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection Randomization using Extension Method [duplicate]

Possible Duplicate:
C#: Is using Random and OrderBy a good shuffle algorithm?

I want to create an extension method which should shuffle the items in the collection.

Can i improve the following?

public static IList<T> RandomList<T>(this IList<T> source)
{
   if (source.Count <= 0) throw new ArgumentException("No Item to Randomize");  

            for (int i =source.Count-1 ; i>0; i--)
            {
                int RandomIndex = Rnd.Next(i + 1);
                T temp = source[i];
                source[i] = source[RandomIndex];
                source[RandomIndex] = temp;
            }

            return source;
 }
like image 963
Russel Avatar asked Feb 28 '23 22:02

Russel


1 Answers

public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
   foreach(var item in source.OrderBy(i => Guid.NewGuid()))
   {
      yield return item;
   }
}
like image 144
BFree Avatar answered Mar 07 '23 20:03

BFree