C# Linq从另一个列表中获取列表

C# Linq从另一个列表中获取列表,c#,linq,join,C#,Linq,Join,我有两个集合:一个是Items,另一个是ActiveItems 这两个集合之间的唯一交集是名称 我想要一个带有Linq from Items的列表,其中项目名称位于具有该名称的ActiveItems中 我写了这段代码有更好的主意吗: Items.Where(i => ActiveItems.Count(v=> v.Name==i.Name) > 0) 我可能会从ActiveItems创建一组名称,然后使用它: var activeNames = new HashSet<

我有两个集合:一个是Items,另一个是ActiveItems

这两个集合之间的唯一交集是名称

我想要一个带有Linq from Items的列表,其中项目名称位于具有该名称的ActiveItems中

我写了这段代码有更好的主意吗:

Items.Where(i => ActiveItems.Count(v=> v.Name==i.Name) > 0)

我可能会从
ActiveItems
创建一组名称,然后使用它:

var activeNames = new HashSet<string>(activeItems.Select(x => x.Name));
var itemsWithActiveNames = items.Where(x => activeNames.Contains(x.Name))
                                .ToList();
请注意,如果存在多个同名的
ActiveItem
值,则这将提供重复的
item
值。另一个替代连接,没有这个问题,但有点笨拙:

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)复杂性。

使用连接:

Items.where(i => ActiveItems.Any(a => i.Name == a.Name))
from item in Items
join active in ActiveItems on item.Name equals active.Name
select item

不,我不想要其他集合的属性解决方案2和3是否会在内部使用哈希集而不将
activeNames
作为一个集合?@Magnus:Yes。。。我发现第一个版本在你不需要连接的时候更清晰:)连接应该是。。。在item.Name上等于active.Name。顺序很重要
var results = from i1 in collection1.Items
              join i2 in collection2.ActiveItems on i1.Name equals i2.Name
              select i2.Name;
from item in Items
join active in ActiveItems on item.Name equals active.Name
select item