【问题标题】:Filter by Key in a Dictionary within a List of objects?在对象列表中的字典中按键过滤?
【发布时间】:2019-03-04 02:54:25
【问题描述】:

我创建了List<YouTubeChannelInfo>,其中包含许多 YouTube 频道列表。

YouTubeChannelInfo 有一个名为“Playlists”的字典属性,其中包含作为键的播放列表标题和作为值的 ID。因此,给定频道可能有许多播放列表。

public class YouTubeChannelInfo
{

    public string Name { get; set; } // Channel Name
    public Dictionary<string, string> Playlists { get; set; } // Key - Playlist Title, Value - Playlist ID
}

我有 string[] playlists,其中包含一系列播放列表标题,并且只需要根据这些播放列表标题过滤 YouTube 频道。

List<YouTubeChannelInfo> youTubeChannelsInfo = GetChannels();
string[] playlists = GetPlaylists();
youTubeChannelsInfo = FilterByPlaylists(youTubeChannelsInfo, playlists); // Anyway to do this ?

如果我可以使用 Linq 过滤它会更好

【问题讨论】:

    标签: c# linq dictionary


    【解决方案1】:

    应该像使用WhereAnyContainsKey 一样简单

    List<YouTubeChannelInfo> youTubeChannelsInfo = GetChannels();
    string[] playlists = GetPlaylists();
    var filtered = youTubeChannelsInfo.Where(x => playLists.Any(y => x.Playlists.ContainsKey(y))).ToList();
    

    【讨论】:

    • 谢谢 :) 这行得通。很高兴你想出了一个 linq 表达式
    猜你喜欢
    • 2022-07-21
    • 2020-04-08
    • 2022-12-02
    • 1970-01-01
    • 2022-08-19
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    相关资源
    最近更新 更多