2016-01-12 86 views
2

我想知道是否有可能从Linq表达式中获得List<IGrouping<string, IGrouping<string, T>>>。我想做的是按流派和艺术家排列歌曲,但是我可以通过每种流派和每种流派迭代的格式,为每张专辑进行迭代。如果可能的话该怎么办?还是有更好的方法来实现我想要实现的目标?与LinQ嵌套IGrouping

这是我的歌类

public class Song 
{ 
    [StringLength(100)] 
    public string Album { get; set; } 

    public int Id { get; set; } 

    [StringLength(100)] 
    public string Title { get; set; } 

    [StringLength(100)] 
    public string Genre { get; set; } 

    [StringLength(255)] 
    public string Comment { get; set; } 

    [StringLength(4)] 
    public string Year { get; set; } 

    [StringLength(100)] 
    public string Author { get; set; } 

    public int Length { get; set; } 

    [StringLength(255)] 
    public string Photo { get; set; } 

    [StringLength(255)] 
    public string FileName { get; set; } 

    public string Extension { get; set; } 
} 

而且此查询我在这里

var songs = db.Songs.GroupBy(s => s.Genre).ToList(); 

给了我一个List<IGrouping<string, Song>>,但我要的是进一步按艺术家。

+0

[Linq Getting Customers group by date,then by type]可能重复(http://stackoverflow.com/questions/19703034/linq-getting-customers-group-by-date-and-then-by-他们的类型) – Clint

回答

3

我想要的是什么结果的List<IGrouping<string, IGrouping<string, Song>>>和该代码给了我正是我想要

  var queryNestedGroups = 
      (from song in db.Songs 
      group song by song.Genre into newGroup1 
      from newGroup2 in 
       (from song in newGroup1 
       group song by song.Author) 
      group newGroup2 by newGroup1.Key).ToList(); 

(虽然我不很确定如何将它翻译成linq方法的语法)。

感谢所有评论和/或回答的人。

+0

其实这很有趣,我从来没有见过这样的用法。 +1 –

+0

@IvanStoev - 是的,这是:)这是[嵌套分组](https://msdn.microsoft.com/en-us/library/bb545974.aspx)。 –

+0

@RahulSingh哈哈,你有我!不知何故,错过了这些信息,谢谢你的链接。不太直观,尤其是** newGroup1.Key **组的** newGroup2 **,想知道它将如何看待第三级,还有方法语法。无论如何。 –

2
var songs = db.Songs.GroupBy(s => s.Genre, (genre, genreGroup) => new 
            { 
             Genre = genre, 
             ArtistGroup = genreGroup.GroupBy(s => s.Artist) 
            }); 

这几乎回到你想要的东西,但是IGrouping<string, IGrouping<string, Song>>只能如果你与你自己的类和new那达,而不是匿名类型上面使用实施IGrouping<K,V>返回。

0

尝试添加第二个分组到第一

var songs = db.Songs.GroupBy(s => s.Artist).SelectMany(s => s.GroupBy (d => d.Genre)).OrderBy (s => s.Key).ToList(); 
+0

我不太清楚这是干什么的,但它仍然会返回一个'List >'。 – Jairo