0

I'm fairly new to C# and trying to create a mp3-player. I'm using a sortedList for the playlist (song name as Key and filepath as Value), but I'm not sure how I can randomize the list order for the shuffle.

I tried this kind of approach, but it doesn't come up with any kind of new order and it removes one song from the list, heh.

private SortedList Shuffle(SortedList oldSongList)
{
    SortedList newSongList = new SortedList();
    Random r = new Random();
    int n = oldSongList.Count;

    while (n > 1)
    {
        int rand = r.Next(n);
        newSongList.Add(oldSongList.GetKey(rand), oldSongList.GetByIndex(rand));
        oldSongList.RemoveAt(rand);
        oldSongList.TrimToSize();
        n--;
    }
    return newSongList;
}

Any thoughts?

Fischermaen
  • 12,238
  • 2
  • 39
  • 56
Seerumi
  • 1,937
  • 3
  • 18
  • 16
  • @Aeshang: Wrong. `new Random()` seeds from `Environment.TickCount` – SLaks Dec 13 '11 at 16:13
  • Honestly... What image pops up in your mind when you type SortedList? – Roy Dictus Dec 13 '11 at 16:15
  • Why would you try to Shuffle a SortedList? A SortedList is by definition sorted, so so it's not really possible to make permutations of that (well equivalent objects might be permutated in different orderss, but other then that) – Grizzly Dec 13 '11 at 16:18

2 Answers2

5

A SortedList is exactly that—sorted.
You can't change its order.

Instead, you should put the items into a List<T> and shuffle it.

Community
  • 1
  • 1
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Using a List instead of SortedList is the best design, but there is a way to do it with a SortedList. Use an IComparer that won't do any actual sorting to make your shuffled list. This IComparer will add each new addition to either the beginning or end of the list. I'm not sure which, since I don't know SortedList's underlying sorting implementation, but it doesn't matter, as either way is acceptable.

public class SuffleSorter : IComparer
{
      int IComparer.Compare( Object x, Object y )  {
          return -1;
      }
}


private SortedList Shuffle(SortedList oldSongList) 
{ 
    SortedList newSongList = new SortedList(new ShuffleSorter()); 
    Random r = new Random(); 
    oldSongList.TrimToSize();
    for (int n = oldSongList.Count; n > 0; n--) 
    { 
        int rand = r.Next(n); 
        newSongList.Add(oldSongList.GetKey(rand), oldSongList.GetByIndex(rand)); 
        oldSongList.RemoveAt(rand); 
        oldSongList.TrimToSize(); 
    } 
    return newSongList; 
} 

Note that this would require making a new, legtimately sorted playlist when the user turns off shuffle (assuming your shuffle is a toggle mode, and not a 1-click "shuffle the playlist" button).

Esoteric Screen Name
  • 6,082
  • 4
  • 29
  • 38