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;
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
foreach(var item in source.OrderBy(i => Guid.NewGuid()))
{
yield return item;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With