C#/Linq:无法按预期工作

jgwigjjp  于 2023-10-13  发布在  C#
关注(0)|答案(1)|浏览(168)

我对Linq技能感到耳目一新,但遇到了一个障碍--第二组没有做我认为应该做的事情。一对一对的分组。键似乎根本不分组,只是整理。它重新排序艺术家,使所有具有相同流派的艺术家按顺序出现,但不对他们进行分组。

// Create a list of pairs of GenreName and ArtistName
var genres_and_artist =
    from artist in db.Artists
    join track in db.Tracks on artist.ArtistId equals track.ArtistId
    join genre in db.Genres on track.GenreId equals genre.GenreId
    group artist by new { genre.GenreId, artist.ArtistName };

// Count up the number of artists in each genre
var genres_by_artist =
    from pair in genres_and_artist
    group pair by pair.Key;

实际:

  • Key { GenreId = 1,ArtistName =“4 Non Blondes”}
  • 组计数= 1
  • 关键字{ GenreId = 1,ArtistName =“亚当和蚂蚁”}
  • 组计数= 1

预期:

  • 关键字{ GenreId = 1,{ ArtistName =“4 Non Blondes”,ArtistName =“Adam and The Ants”} }
  • 组计数= 2
nbnkbykc

nbnkbykc1#

如果我没理解错的话,你是在找一份不同流派的艺术家名单。当你把艺术家的名字按GenreId分组时,你已经接近了:

var genres_and_artist =
    from artist in db.Artists
    join track in db.Tracks on artist.ArtistId equals track.ArtistId
    join genre in db.Genres on track.GenreId equals genre.GenreId
    group artist.ArtistName by genre.GenreId;

这会产生这样的组,其中艺术家乘以他们在流派中拥有的歌曲数量(事实上,它是按GenreId分组的歌曲,但只显示歌曲的艺术家名称),所以剩下的就是让名称不同,或者通过......

var artists_by_genre =
    from grouping in genres_and_artist
    select new
    {
        GenreId = grouping.Key,
        Artists = grouping.Distinct()
    };

或者...

var artists_by_genre =
    from grouping in genres_and_artist
    select new
    {
        GenreId = grouping.Key,
        Artists = grouping.GroupBy(name => name).Select(g => g.Key)
    };

相关问题