使用LINQ获取两个IEnumebles的交集

5 c# linq

我有两个类型的实例IEnumerable如下.

IEnumerable<Type1> type1 = ...;
IEnumerable<Type2> type2 = ...;
Run Code Online (Sandbox Code Playgroud)

双方Type1并Type2包含一个称为成员common,因此,即使它们是不同类的,我们仍然可以涉及他们这样.

type1[0].common == type2[4].common
Run Code Online (Sandbox Code Playgroud)

我试图过滤那些type1没有相应common值的元素,type2并根据每个元素中的一个值创建一个字典.现在,我通过以下双循环来做到这一点.

Dictionary<String, String> intersection = ...;
foreach (Type1 t1 in type1)
  foreach(Type2 t2 in type2)
    if (t1.common == t2.common)
      intersection.Add(t1.Id, t2.Value);
Run Code Online (Sandbox Code Playgroud)

现在,我已经试过LINQ但所有的.Where,.Select而.ForEach只是给了我头痛.有没有办法使用LINQ巧妙地执行相同的操作?

Eri*_*ert 15

当两个序列有共同点并且您希望根据该共性过滤其产品时,高效查询是一个连接.假设Type1是Customer,Type2是Order.每个客户都有一个CustomerID,每个订单也有一个CustomerID.然后你可以这样说.

var query = from customer in customers
            join order in orders 
              on customer.CustomerId equals order.CustomerId
            select new { customer.Name, order.Product };
Run Code Online (Sandbox Code Playgroud)

迭代将为您提供一系列配对,包括每个有订单的客户名称及其所有产品.因此,如果顾客Suzy订购了煎饼和披萨,而顾客鲍勃订购了牛排,那么你就会得到这些牛排.

Suzy, pancake
Suzy, pizza
Bob, steak
Run Code Online (Sandbox Code Playgroud)

如果您希望这些分组,以便每个客户都有他们的订单列表,那就是组加入.

var query = from customer in customers
            join order in orders 
              on customer.CustomerId equals order.CustomerId 
              into products
            select new { customer.Name, products };
Run Code Online (Sandbox Code Playgroud)

迭代可以为您提供第一项是名称的对,第二项是一系列产品.

Suzy, { pancake, pizza }
Bob, { steak }
Run Code Online (Sandbox Code Playgroud)