Using [0] or First() with LINQ OrderBy

2019-05-31 05:50发布

问题:

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")

回答1:

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;


回答2:

LINQ has two ways to query "from . in .." and Lambda expressions. They way you were almost writing it looked Lambda-ish. Here would be the Lambda expression:

albums.OrderBy(a=>a.Discs.First().Tracks.First().Title)

I used variable 'a' to indicate album but you can use any variable, this is identical to the first expression:

albums.OrderBy(album=>album.Discs.First().Tracks.First().Title)

or you can use the from obj in obj form as mention in the other answers.



回答3:

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;


回答4:

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.