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?
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.