Home > Blockchain >  Searching 2 different Lists via Linq
Searching 2 different Lists via Linq

Time:09-15

I have 2 different IEnumerables:

IEnumerable<TypeA> ListA & IEnumerable<TypeB> ListB

Both types have the property called "PersString".

My goal is to get for each item in ListA the corresponding items of ListB with the same "PersString".

I started with a ForEach-Loop in ListA nesting a ForEach-Loop of ListB and checking if "PersString" of the ListA-item matches the "PersString" of the ListB-item.

Is there a more efficient way of coding using Linq ?

Thank you.

CodePudding user response:

Is there a more efficient way of coding using Linq ?

Yes, you can join them. In Linq-To-Object this is (much) more efficient:

var query = from a in ListA 
            join b in ListB on a.PersString equals b.PersString
            select (A: a, B: b);

CodePudding user response:

Join is more efficient way

var result = from x in ListA
                     join y in ListB
                on x.PersString equals y.PersString
                     select new {x,y};
  •  Tags:  
  • c#
  • Related