Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way of randomly re-arranging a list of items in c#?

Tags:

c#

.net

random

I have a list of objects and I want to reorder them randomly on each request. What is the best way of doing this?

like image 463
Arron S Avatar asked Jan 06 '09 19:01

Arron S


2 Answers

How about some kind of Knuth-Fisher-Yates shuffle algorithm ?

for (int i = cards.Length - 1; i > 0; i--)
{
    int n = rand.Next(i + 1);
    Swap(ref cards[i], ref cards[n]);
}

Code taken from Coding Horror. This is also a recommended reading on how people often do this wrong.

like image 81
Gant Avatar answered Nov 14 '22 22:11

Gant


Check out this cool Linq way of doing it:

public class Employee
{
    public int Id
    {
        get;
        set;
    }
    public string Name
    {
        get;
        set;
    }
}

Populate a list:

    List<Employee> list = new List<Employee>();

    list.Add(new Employee { Id = 1, Name = "Davolio Nancy" });
    list.Add(new Employee { Id = 2, Name = "Fuller Andrew" });
    list.Add(new Employee { Id = 3, Name = "Leverling Janet" });
    list.Add(new Employee { Id = 4, Name = "Peacock Margaret" });
    list.Add(new Employee { Id = 5, Name = "Buchanan Steven" });
    list.Add(new Employee { Id = 6, Name = "Suyama Michael" });
    list.Add(new Employee { Id = 7, Name = "King Robert" });
    list.Add(new Employee { Id = 8, Name = "Callahan Laura" });
    list.Add(new Employee { Id = 9, Name = "Dodsworth Anne" });

Then sort:

    list = list.OrderBy(emp => Guid.NewGuid()).ToList();

Credit

like image 23
BFree Avatar answered Nov 14 '22 20:11

BFree