0

Possible Duplicate:
Randomize a List<T> in C#

Let's suppose that I have

List<SomeClass> _myList;

and I populate _myList with ordered collection of objects. Now, I would like to shuffle them. How?

I was thinking of using

_myList.Sort( (a,b) => r.GetNext() - 0.5 );

but I suppose that can work only on SOME implementations of Sort().

BTW, r = new Random();

BTW2, my lists are thousands elements large...

Community
  • 1
  • 1
Daniel Mošmondor
  • 19,718
  • 12
  • 58
  • 99
  • 1
    See http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp and http://stackoverflow.com/questions/375351/most-efficient-way-to-randomly-sort-shuffle-a-list-of-integers-in-c-sharp – flipchart Oct 27 '11 at 07:12
  • I think you need [this][1] [1]: http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp – luqi Oct 27 '11 at 07:14
  • See also http://stackoverflow.com/questions/1287567/c-is-using-random-and-orderby-a-good-shuffle-algorithm – MartinStettner Oct 27 '11 at 07:44

3 Answers3

3
_myList.OrderBy(item => r.Next());

Should return you the list's items in random order.

vc 74
  • 37,131
  • 7
  • 73
  • 89
0

u look some thing like this.

private List<E> ShuffleList<E>(List<E> inputList)
{
     List<E> randomList = new List<E>();

     Random r = new Random();
     int randomIndex = 0;
     while (inputList.Count > 0)
     {
          randomIndex = r.Next(0, inputList.Count); //Choose a random object in the list
          randomList.Add(inputList[randomIndex]); //add it to the new, random list
          inputList.RemoveAt(randomIndex); //remove to avoid duplicates
     }

     return randomList; //return the new random list
}
4b0
  • 21,981
  • 30
  • 95
  • 142
0

Here's an idea, extend IList in a (hopefully) efficient way.

public static IEnumerable<T> Shuffle<T>(this IList<T> list)
{
    var choices = Enumerable.Range(0, list.Count).ToList();
    var rng = new Random();
    for(int n = choices.Count; n > 1; n--)
    {
        int k = rng.Next(n);
        yield return list[choices[k]];
        choices.RemoveAt(k);
    }
    yield return list[choices[0]];
}
Jodrell
  • 34,946
  • 5
  • 87
  • 124