How to select objects from a list that has a property that matches an item in another list?
linq, list, windows-phone-7
Solution
You can use `List.Contains` in a `Where` clause:
public Lists()
{
SelectedChannels = AllChannels
.Where(channel => SelectedChannelIds.Contains(channel.ChannelId))
.ToList();
}
Note that it would be more efficient if you used a `HashSet<int>` instead of a `List<int>` for the `SelectedChannelIds`. Changing to a `HashSet` will improve the performance from O(n2) to O(n), though if your list is always quite small this may not be a significant issue.
Problem
Hard question to understand perhaps, but let me explain. I have a `List` of `Channel`-objects, that all have a `ChannelId` property (`int`). I also have a different `List` (`int`) - `SelectedChannelIds`, that contains a subset of the `ChannelId`-s. I want to select (through `LINQ`?) all the `Channel`-objects that has a `ChannelId`-property matching one in the second `List`. in other words, I have the following structure: ``` public class Lists { public List<Channel> AllChannels = ChannelController.GetAllChannels(); public List<int> SelectedChannelIds = ChannelController.GetSelectedChannels(); public List<Channel> SelectedChannels; // = ????? } public class Channel { // ... public int ChannelId { get; set; } // ... } ``` Any ideas on what that LINQ query would look like? Or is there a more effective way? I'm coding for the Windows Phone 7, fyi.