这个问题也许很难理解,但让我解释一下。我有一个List
的Channel
- 对象,所有对象都有 ChannelId
属性(property)( int
)。我也有一个不同的List
( int
) - SelectedChannelIds
,包含 ChannelId
的子集-s。
我想选择(通过LINQ
?)所有Channel
-具有 ChannelId
的对象-第二个匹配一个的属性 List
.
换句话说,我有以下结构:
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; }
// ...
}
关于 LINQ 查询的外观有什么想法吗?或者有更有效的方法吗?我正在为 Windows Phone 7 编写代码,仅供引用。
最佳答案
您可以使用 List.Contains
在 Where
子句:
public Lists()
{
SelectedChannels = AllChannels
.Where(channel => SelectedChannelIds.Contains(channel.ChannelId))
.ToList();
}
请注意,如果您使用HashSet<int>
,效率会更高。而不是List<int>
对于SelectedChannelIds
。更改为 HashSet
会将性能从 O(n2) 提高到 O(n),但如果您的列表总是很小,这可能不是一个重大问题。
关于linq - 如何从列表中选择具有与另一个列表中的项目匹配的属性的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10209674/