Correctly using LINQ to shuffle a deck
LINQ methods are not mutating existing collections. So this statement does nothing at all: this.OrderBy(a => Guid.NewGuid());
Also, I'm pretty sure you can't assign to this
, so you have to either don't inherit from List<T>
(which is good), or do something like this:
var sorted = this.OrderBy(a => Guid.NewGuid()).ToList();
this.Clear();
this.AddRange(sorted);
Also look at this SO answer, there is more correct shuffling algorithm.
Use this extension method
public static class Extensions
{
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
{
Random rnd = new Random();
return source.OrderBy((item) => rnd.Next());
}
}
Try this
public void Shuffle()
{
Random r = new Random();
this.Sort((x, y) => r.Next(-1, 1));
}
Because of Linq's deffered execution following line doesn't get executed.
this.OrderBy(a => Guid.NewGuid());
This just creates the query but never executed. Even if executed it won't change your collection.
Don't forget Linq is a way to query data, not mutate it.