2

I have an ObservableCollection with objects. I want to randomize the order of the collection. How can I do that?

FVen
  • 53
  • 1
  • 4
  • Possible duplicate of [Returning items randomly from a collection](http://stackoverflow.com/questions/1866533/returning-items-randomly-from-a-collection) – Fruchtzwerg Jun 30 '16 at 11:47

1 Answers1

3

You could use an extension method to do that. You can add this class to you project to provide an extension method for collections. It's a simple shuffle.

public static class ShuffleExtension
{
    public static void Shuffle<T>(this IList<T> list)
    {
        Random rng = new Random();
        int n = list.Count;
        while (n > 1)
        {
            n--;
            int k = rng.Next(n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
}

To use, call yourcollection.Shuffle().

Martin Tirion
  • 1,246
  • 1
  • 7
  • 10