Arron S
Arron S

Reputation: 5537

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

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

Upvotes: 6

Views: 424

Answers (7)

Geries Handal
Geries Handal

Reputation: 63

Try this code here

It uses the IComparer.Compare

It will be a good practice if you do the function using generics

Upvotes: 0

BCS
BCS

Reputation: 78506

My favorite solution to shuffling stuff is use an N*log N sort and pass it a sort predicate that returns a random result. It has the nice feature that is can be done with a minimum of new code using building blocks that most languages have handy in even the most striped versions.

Upvotes: 1

BFree
BFree

Reputation: 103742

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

Upvotes: 6

Germstorm
Germstorm

Reputation: 9839

I would create a new List and filling it with items that are randomly selected and removed from the original List.

Upvotes: 0

abelenky
abelenky

Reputation: 64672

Let me direct you to one WRONG way of doing it, and a way I confess I used before, and never saw the error of it until this blog post:

http://www.codinghorror.com/blog/archives/001015.html

Upvotes: 2

Gant
Gant

Reputation: 29889

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.

Upvotes: 12

dalle
dalle

Reputation: 18507

You could use the Fisher-Yates shuffle algorithm which runs in linear-time.

Upvotes: 2

Related Questions