【问题标题】:Refactor similar Linq Queries [closed]重构类似的 Linq 查询 [关闭]
【发布时间】:2020-01-26 12:27:22
【问题描述】:

重构这些方法有什么意义吗?怎么做?

    public IEnumerable<Game> GetGamesByGenre(string genre)
    {
        return Games.Where(x => x.SubGenre.Genre.GenreName == genre);
    }

    public IEnumerable<Game> GetGamesBySubGenre(string subGenre)
    {
        return Games.Where(x => x.SubGenre.SubGenreName == subGenre);
    }

【问题讨论】:

    标签: c# asp.net linq


    【解决方案1】:

    你可以引入一个名为propertySelector的新参数:

    public IEnumerable<Game> GetGamesBy(Func<Game, string> propertySelector, string genre)
    {
        return Games.Where(x => propertySelector(x) == genre);
    }
    

    您分别这样调用原始方法:

    GetGamesBy(x => x.SubGenre.Genre.GenreName, someGenreName)
    
    GetGamesBy(x => x.SubGenre.SubGenreName, someSubGenreName)
    

    但是IMO,如果只是这两个方法,以这个小代码为主体,不太值得重构。

    【讨论】:

      【解决方案2】:

      你可以试试这个方法

      public IEnumerable<Game> GetGames(string? genre, string? subGenre)
      {
          return Games.Where(x => (String.IsNullOrEmpty(genre) || x.SubGenre.Genre.GenreName == genre) 
                         && (String.IsNullOrEmpty(subGenre) || x.SubGenre.SubGenreName == subGenre));
      }
      

      【讨论】:

        猜你喜欢
        • 2010-10-26
        • 2011-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多