Linq从另一个列表中获取列表 [英] Linq getting a list from another list
问题描述
我有两个集合:一个是Items,另一个是ActiveItems
I have two collections: one is Items And Another is ActiveItems
这两个集合之间唯一的交集是名称
The only intersection between these two collection is Name
我想要一个包含Linq的项目列表,其中项目名称位于具有该名称的ActiveItems中
I want a list with Linq from Items where the Items names are in the ActiveItems with that name
我写这段代码有一个更好的主意:
I wrote this code is there a better idea:
Items.Where(i => ActiveItems.Count(v=> v.Name==i.Name) > 0)
推荐答案
我可能会从ActiveItems
创建一组名称,然后使用它:
I would probably create a set of the names from ActiveItems
and then use that:
var activeNames = new HashSet<string>(activeItems.Select(x => x.Name));
var itemsWithActiveNames = items.Where(x => activeNames.Contains(x.Name))
.ToList();
另一种选择是使用联接,例如带有查询表达式:
Another option is to use a join, e.g. with a query expression:
var query = from activeItem in activeItems
join item in items on activeItem.Name equals item.Name
select item;
请注意,如果存在多个具有相同名称的ActiveItem
值,这将给出重复的item
值.另一个替代联接,它没有这个问题,但是有点笨拙:
Note that this will give duplicate item
values if there are multiple ActiveItem
values with the same name. Another alternative join, which doesn't have this problem but is a bit clumsier:
var query = from item in items
join activeItem in activeItems
on item.Name equals activeItem.Name
into g
where g.Any()
select item;
请注意,所有这些都将避免O(N * M)检查名称-它们都将在后台使用哈希表,从而带来O(N + M)的复杂性.
Note that all of these will avoid the O(N * M) check for names - they'll all use hash tables behind the scenes, to give an O(N + M) complexity.
这篇关于Linq从另一个列表中获取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!