Getting the intersection of two IEnumerables using LINQ

I have two type instances IEnumerableas follows.

IEnumerable<Type1> type1 = ...;
IEnumerable<Type2> type2 = ...;

Both Type1and Type2contain a member called common, so, even though they are of different class, we can still link them as follows.

type1[0].common == type2[4].common

I am trying to filter out those elements Type1that do not have a corresponding value commonin Type2, and create a dictionary based on one value from each. Right now, I am doing this with the following double loop.

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);

Now I tried with LINQ, but that’s all .Where, .Selectand .ForEachjust gave me a headache. Is there a way to neatly perform the same operation using LINQ?

+5
source share
5

- , , - . , 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 };

, , , , . , , , .

Suzy, pancake
Suzy, pizza
Bob, steak

, , , .

var query = from customer in customers
            join order in orders 
              on customer.CustomerId equals order.CustomerId 
              into products
            select new { customer.Name, products };

, , - , - .

Suzy, { pancake, pizza }
Bob, { steak }
+14

. , . , .

public class Type1
{
    public string ID { get; set; }
    public Guid common { get; set; }
}
public class Type2
{
    public string Value { get; set; }
    public Guid common { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Guid CommonGuid = Guid.NewGuid();

        IEnumerable<Type1> EnumType1 = new List<Type1>()
        {
            new Type1() {
                ID = "first",
                common = CommonGuid
            },
            new Type1() {
                ID = "second",
                common = CommonGuid
            },
            new Type1() {
                ID = "third",
                common = Guid.NewGuid()
            }
        } as IEnumerable<Type1>;

        IEnumerable<Type2> EnumType2 = new List<Type2>()
        {
            new Type2() {
                Value = "value1",
                common = CommonGuid
            },
            new Type2() {
                Value = "value2",
                common = Guid.NewGuid()
            },
            new Type2() {
                Value = "value3",
                common = CommonGuid
            }
        } as IEnumerable<Type2>;

        //--The part that matters
        EnumType1                       //--First IEnumerable
            .Join(                      //--Command
                EnumType2,              //--Second IEnumerable
                outer => outer.common,  //--Key to join by from EnumType1
                inner => inner.common,  //--Key to join by from EnumType2
                (inner, outer) => new { ID = inner.ID, Value = outer.Value })  //--What to do with matching "rows"
            .ToList()   //--Not necessary, just used so that I can use the foreach below
            .ForEach(item =>
                {
                    Console.WriteLine("{0}: {1}", item.ID, item.Value);
                });

        Console.ReadKey();
    }
}

:
first: value1
first: value3
second: value1
second: value3

+1

Assuming you still want to keep the intersection as Dictionary<string, string>:

IEnumerable<Type1> list1;
IEnumerable<Type2> list2;

Dictionary<string, string> intersection = 
    (from item1 in list1
     from item2 in list2
     where item1.common = item2.common
     select new { Key = item1.Id, Value = item2.Value })
         .ToDictionary(x => x.Key, x => x.Value);
0
source
type1.where(i=>type2.where(j=>j.common == i.common).Count > 0);

This will give you a list of only those that match.

-1
source

I will miss something, but I will do the following:

type1
 .where(t1 => type2.Any(t2 => t1.common == t2.common)
 .ToDictionary(t1 => t1.Id)

Or as suggested by Servy

type1
  .Join(type2, a => a.common, b => b.common, (a1,b1) => a1)
  .ToDictionary(t1 => t1.Id)
-1
source

All Articles