Linq 如何从属性与另一个列表中的项目匹配的列表中选择对象?
这个问题也许很难理解,但让我解释一下。我有一个Linq 如何从属性与另一个列表中的项目匹配的列表中选择对象?,linq,list,windows-phone-7,Linq,List,Windows Phone 7,这个问题也许很难理解,但让我解释一下。我有一个列表的通道-对象,它们都有一个ChannelId属性(int)。我还有一个不同的列表(int)-selectedchannelid,它包含ChannelId-s的子集 我想(通过LINQ?)选择第二个列表中具有ChannelId-属性匹配的所有Channel-对象 换句话说,我有以下结构: public class Lists { public List<Channel> AllChannels = ChannelControll
列表
的通道
-对象,它们都有一个ChannelId
属性(int
)。我还有一个不同的列表
(int
)-selectedchannelid
,它包含ChannelId
-s的子集
我想(通过LINQ
?)选择第二个列表中具有ChannelId
-属性匹配的所有Channel
-对象
换句话说,我有以下结构:
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; }
// ...
}
公共类列表
{
public List AllChannels=ChannelController.GetAllChannels();
public List SelectedChannelIds=ChannelController.GetSelectedChannels();
公共列表所选频道;//=?????
}
公共类频道
{
// ...
公共int ChannelId{get;set;}
// ...
}
关于LINQ查询的样子有什么想法吗?还是有更有效的方法?我正在为Windows Phone 7编码,仅供参考。您可以在Where
子句中使用:
public Lists()
{
SelectedChannels = AllChannels
.Where(channel => SelectedChannelIds.Contains(channel.ChannelId))
.ToList();
}
请注意,如果对所选ChannelId
使用哈希集而不是列表,则效率会更高。更改为HashSet
会将性能从O(n2)提高到O(n),但如果列表总是很小,这可能不是什么大问题。SelectedChannels=new list(AllChannels.Where(c=>SelectedChannelIds.Contains(c.ChannelId));
SelectedChannels = new List<Channel>(AllChannels.Where(c => SelectedChannelIds.Contains(c.ChannelId)));
Mark-感谢您提供了一个很好且内容丰富的答案。我的名单永远不会超过140张,通常是40张左右。这仍然是一种性能提升吗?