Search code examples
c#sortingwindows-phone-8

How to sort Song Library in track number order


I'd like to make some easy player for Windows Phone but I observed that SongLibrary is sorted by alphabetic (so stupid, I think). So my question is that how I can sort it by Track Number?

if I do next:

        MediaLibrary library = new MediaLibrary();
        songCollection = library.Songs;

the songCollection has all songs but in alphabetic order. So what next? I tried to understand "OrderBy method" but it made me just too confused.


Solution

  • You can use LINQ to Objects and OrderBy method. What you need is a delegate and the easiest way to get one is by using lambda expression.

    List<Song> orderedSongs = songCollection.OrderBy(s => s.TrackNumber).ToList();
    

    Additional ToList() call will cause the query execution and will materialize a list, so any time you refer to orderedSongs ordering will not be performed over and over again.

    You could get the same using syntax based query:

    List<Song> orderedSongs = (from s in songCollection
                               orderby s.TrackNumber
                               select s).ToList();