Using [0] or First() with LINQ OrderBy

岁酱吖の 提交于 2019-12-07 03:43:24

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;

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.

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;

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!