Senura Dissanayake
Senura Dissanayake

Reputation: 663

Filter by Key in a Dictionary within a List of objects?

I have created List<YouTubeChannelInfo> which contains many List of YouTube Channels.

YouTubeChannelInfo has a Dictionary attribute called 'Playlists' which contains Playlist Title as the key and the ID as the value. Thus there could be many playlists for a given channel.

public class YouTubeChannelInfo
{

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

I have string[] playlists which contains an array of playlist titles and need to filter only the YouTube Channels based on those playlist titles.

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

It will be better if I can filter that by using Linq

Upvotes: 0

Views: 55

Answers (1)

TheGeneral
TheGeneral

Reputation: 81583

It should be as simple as using Where and Any, and ContainsKey

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

Upvotes: 2

Related Questions