什么时候调用OrderBy运算符?

时间:2011-09-14 19:27:56

标签: linq linq-to-objects

1) 一个)

    var result1 = from artist in artists
                  from album in artist.Albums
                  orderby album.Title,artist.Name
                  select new { Artist_id = artist.id, Album_id = album.id };

以上查询是否翻译成:

        var result = artists.SelectMany(p => p.albums
            .Select(p1 => new { Artist = p, Album = p1 }))
            .OrderBy(p2 => p2.Album.Title)
            .ThenBy(p3 => p3.Artist.Name)
            .Select(p4 => new { Artist_id = p4.Artist.id, Album_id = p4.Album.id });

b)中 我不确定这个问题是否有意义 - 如果我的假设是正确的,因此OrderBy总是被调用的最后一个运算符之一(当使用查询表达式时),那么我们如何表达以下代码使用查询表达式(换句话说,我们如何在查询表达式中指定我们希望OrderBy运算符更快地被调用而不是最后一个运算符之一):

        var result = artists
            .SelectMany(p1 => p1.albums
                .OrderBy(p2=>p2.title)
                .Select(p3 => new { ID = p3.id, Title = p3.title }));

2)在以下查询表达式中,将两个orderby子句转换为OrderBy(... artist.Name).OrderBy( ... album.Title)

        var result1 = from artist in artists
                      from album in artist.Albums
                      orderby artist.Name
                      orderby album.Title
                      select new { ...};

谢谢

1 个答案:

答案 0 :(得分:2)

对于问题1:orderby会在您显示的任何地方被调用。您的查询与您展示的内容并不完全相同,但它很接近。将它格式化以使其看起来就像在SelectMany的结果上调用Select一样没有帮助,当它实际上在上时参数到SelectMany。您的查询被翻译为更像:

var result = artists
    .SelectMany(artist => artist.albums, (artist, album) => new {artist, album})
    .OrderBy(z => z.album.Title)
    .ThenBy(z => z.artist.Name)
    .Select(z => new { Artist_id = z.artist.id, Album_id = z.album.id }

问题1b)您的查询大致等同于:

var result = from p1 in artists
             from p3 in (from p2 in p1.albums
                         orderby p2.title
                         new { ID = p2.id, Title = p2.title }) 
             select p3;

这只是一个粗略的翻译,因为在我记忆中,查询表达式中的任何内容都没有转换为SelectMany的重载。另一方面,它可能会以稍微简单的方式完成您想要的任务:

var result = from p1 in artists
             from p3 in p1.albums.OrderBy(p2 => p2.title)
             select new { ID = p3.id, Title = p3.title };

您仍会在艺术家中获得订购。它是查询表达式和“点符号”的混合,但它对我来说很好看。很遗憾你在最终结果中没有使用p1,请注意......

对于问题2,使用两个orderby子句确实可以获得两个OrderBy次调用,这几乎可以肯定不是你想要的。你想要:

var result1 = from artist in artists
              from album in artist.Albums
              orderby artist.Name, album.Title
              select new { ...};

这会被转换为适当的OrderBy(...).ThenBy(...)来电。