【问题标题】:selecting items from a list with linq, where items appear in other two lists使用 linq 从列表中选择项目,其中项目出现在其他两个列表中
【发布时间】:2011-10-17 08:13:15
【问题描述】:

我有两个包含 guid 的列表:

    var activeSoftware = channels.ByPath("/software/").Children.Where(c => c.StateProperties.IsActive).Select(c => c.Guid);
    var activeChannels = channels.ByPath("/game-channels/").Children.Where(c => c.StateProperties.IsActive).Select(c => c.Guid);

还有另一个游戏列表:

List<MyCms.Content.Games.Game> games = new List<MyCms.Content.Games.Game>();

游戏对象有两个可以使用的属性:

game.gamingproperties.software - 包含软件的 guid game.stateproperties.channels - 逗号分隔的 guid 列表

是的,我知道在字段中保存逗号分隔值并不好, 但我目前无法更改它(它已经在 40 多个网站上运行)

我想要做的是选择软件处于活动状态的所有游戏(通过比较 softwarelistgame.gamingproperties.software)并且它们出现的频道处于活动状态(通过检查 game.stateproperties.channels 是否包含 @ 987654328@指导)

最初,我是这样做的:

    foreach (var channel in activeSoftware)
    {
        foreach (var match in oGames.AllActive.Where(g => !string.IsNullOrEmpty(g.GamingProperties.UrlDirectGame) && g.GamingProperties.Software.Contains(channel) && g.StateProperties.Channels.Split(',').Intersect(activeChannels).Any()))
        {
            games.Add(match);
        }
    } 

但我确信我可以摆脱那些讨厌的 foreach 并只使用 linq。

【问题讨论】:

    标签: linq contains where any


    【解决方案1】:

    您的对象模型确实看起来有点奇怪,所以我认为可以对其进行一些重构,但这是我的答案:

    var query =
        from channel in activeSoftware
        from match in oGames.AllActive
        where !string.IsNullOrEmpty(match.GamingProperties.UrlDirectGame)
        where match.GamingProperties.Software.Contains(channel)
        where match.StateProperties.Channels.Split(',').Intersect(activeChannels).Any()
        select match;
    
    var games = query.ToList();
    

    如果我正确理解您的模型,您也可以这样做:

    var query =
        from match in oGames.AllActive
        where !string.IsNullOrEmpty(match.GamingProperties.UrlDirectGame)
        where match.GamingProperties.Software.Intersect(activeSoftware).Any()
        where match.StateProperties.Channels.Split(',').Intersect(activeChannels).Any()
        select match;
    
    var games = query.ToList();
    

    希望对您有所帮助。

    【讨论】:

    • 你怎么觉得对象模型有点奇怪?
    • 只是match.GamingProperties.Softwarematch.StateProperties.Channels 似乎有点啰嗦,而且不太清楚它们的目的。我必须在一定程度上根据信仰提供答案。
    【解决方案2】:

    看起来您的解决方案可以使用一些重构...但这里有一些粗略的东西可以给您这个想法。

    var new items = items.ForEach(channel => 
    from g in oGames.AllActive
    where (.Where(g => !string.IsNullOrEmpty(g.GamingProperties.UrlDirectGame) && g.GamingProperties.Software.Contains(channel) && g.StateProperties.Channels.Split(',')
         .Intersect(activeChannels).Any())))    
     games.add(items);
    

    如果您希望我更具体,请发布类定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-14
      • 2023-01-17
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多