views:

739

answers:

3

If I have a structure like this

 Albums
    - Album
        - Discs
            - Tracks

and I want to order a collection of albums by the title of the first track on the first disc.

Is there something similar to the following I could do (keeping in mind I need to use the OrderBy extension method that accepts a string)?

albums.OrderBy("Discs[0].Tracks[0].Title")

I need to be able to sort using a string expression thus the need to use the OrderBy method i.e. albums.OrderBy("Track[0].Title"). The reason for this is our custom framework uses a sort expression (e.g. "Title") passed back from a GridView which is looked up in a dictionary (e.g. "Track[0].Title") to get the correct order by clause. That is, the field and direction of sorting is dynamically determined at runtime.

or

albums.OrderBy("Discs.First().Tracks.First().Title")
+3  A: 

Untested, but how about:

    var query = from album in albums
                let disc = album.Discs.First()
                let track = disc.Tracks.First()
                orderby track.Title
                select album;
Marc Gravell
Unfortunately I can't use orderby inline in the query. It needs to be applied after the initial query. I tried using the your query with the orderby line removed and substituting instead using query = query.OrderBy("track.Title") but that didn't work.
A: 

How about this, in order to satisfy your need for an initial query that does not perform the sorting? This uses anonymous types to store the album information, plus the name of the first track so you can sort on it later.

var query = from album in albums
            let disc = album.Discs.First()
            let track = disc.Tracks.First()
            select new { Album = album, FirstTrack = track.Title };

var sortedQuery = from album in query
                  order by album.FirstTrack
                  select album.Album;
Andrew Arnott
I need to use the query.OrderBy(string) method what is used for ordering is dynamically determined at runtime. Sorry, I probably should have made this more clear in the original question.
A: 

Sorry people,

It looks like the OrderBy method that I am asking about and trying to use is specific to the ORM (genom-e) that we are using and is not reflected on the .net Queryable or IEnumerable classes (unlike the majority of genom-e's LINQ functionality). There is no OrderBy overload that accepts a string in .net, this is specific to genom-e.

Those of you using .net encountering a similar problem should probably give either of the above two answers a try.