C# - Randomizing a List

C# - Randomizing a List<T>

c#, list, random

Randomizing a list<T> can be done using the Random and a simple LINQ query. Check out our card shuffling example below:

Randomizing a list of objects

Given a Card class

public class Card {
    public string Name { get; set; }
    public int Value { get; set; }
}

Initialize a new list of cards

var cards = new List<Card>() {
    new Card() { Name = "Jack", Value = 10 },
    new Card() { Name = "Queen", Value = 10 },
    new Card() { Name = "King", Value = 10 },
    new Card() { Name = "One", Value = 1 },
    new Card() { Name = "Two", Value = 2 },
    new Card() { Name = "Three", Value = 3 }
}; 

Shuffle the cards using Random

var rnd = new Random();
var shuffledCards = cards.OrderBy(a => rnd.Next());
//Do something with shuffledCards