【问题标题】:How to group by Games and select each game's list of Genres [duplicate]如何按游戏分组并选择每个游戏的流派列表[重复]
【发布时间】:2020-02-28 19:14:51
【问题描述】:

我正在尝试为多对多 ViewModel GameGenre 创建一个视图,但我不确定如何设计 mvc 以选择所有游戏并按游戏分组但显示每个游戏的所有类型。

我正在寻找如何通过 LINQ 和 group-by 来实现我的目的,但我发现的大多数答案都是将它用于一个模型。

另外,我对我现在拥有的视图模型没有信心:

    public class GameStoreViewModel
    {
        [Key]
        public Guid GameId { get;}
        public string GameName { get;}
        public Genre Genre { get; set; }
        public IEnumerable<Genre> GenreList { get; set; }
    }

这些是我的模型:

    public class Game
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
    }
    public class Genre
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
    }
    public class GameGenre
    {
        public Guid Id { get; set; }
        public Guid GameId { get; set; }
        public Guid GenreId { get; set; }
        public Game Game { get; set; }
        public Genre Genre { get; set; }
    }

在 SQL 上运行的基本查询是:

SELECT ga.Id, ga.Name, ge.Name FROM Game ga
LEFT JOIN GameGenre gg ON ga.Id = gg.GameId
LEFT JOIN Genre ge ON ge.Id = gg.GenreId;

结果

但这会导致游戏重复多次,这对于前店来说看起来并不好。所以,我想让每个游戏都有它的所有类型,比如

比起html视图,我更关心视图模型和控制器代码。

抱歉,如果我的解释不清楚,请告诉我。感谢您的帮助,并提前感谢您!

【问题讨论】:

    标签: c# asp.net-mvc linq group-by


    【解决方案1】:

    你想要这个吗?

    public class Game
    {
        public string GameId { get; set; }
        public string GenreId { get; set; }
    }
    
    var list = new List<Game>{
        new Game { GameId = "Final Fantasy VII", GenreId = "RPG" },
        new Game { GameId = "Dark Souls", GenreId = "RPG" },
        new Game { GameId = "Dark Souls", GenreId = "Action" },
        new Game { GameId = "World of Warcraft", GenreId = "MMORPG" },
        new Game { GameId = "Resident Evil 2", GenreId = "Survival" },
        new Game { GameId = "Resident Evil 2", GenreId = "Horror" }
    };
    
    var groupedList = list.GroupBy(
        g => g.GameId,
        g => g.GenreId,
        (key, group) => new
            {
                GameId = key,
                Genres = group.ToList()
            })
         .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      相关资源
      最近更新 更多