Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to compare two lists of objects where one object has several lists

Tags:

c#

linq

public class MyObject1
{
    public  Guid g1;
    public Guid g2;
    public Guid g3;
}

public class MyObject2
{
    public Guid g4;
}


List<MyObject1> list1;
List<MyObject2> list2;

I would like a LINQ query that would return all MyObject1 objects in list1 where MyObject1.g2 == MyObject2.g4 where the MyObject2 objects live in list 2

i have written code that does this in numerous steps but i would think i could do it in one iteration.

so something like

var n = list1.Select(p=> p.g2).ToList()

var o = list2.Intersect(n)

but now i need to research list1 using o again which is awkward

like image 636
KCIsLearning Avatar asked Apr 05 '13 21:04

KCIsLearning


3 Answers

It sounds like you want a join:

var query = from x1 in list1
            join x2 in list2 on x1.g2 equals x2.g4
            select x1;

Or in extension method syntax:

var query = list1.Join(list2, x1 => x1.g2, x2 => x2.g4, (x1, x2) => x1);

Note that this will only give you the items from list1 - if you need the corresponding item from list2 as well, that's simple:

var query = from x1 in list1
            join x2 in list2 on x1.g2 equals x2.g4
            select new { x1, x2 };
like image 98
Jon Skeet Avatar answered Oct 20 '22 04:10

Jon Skeet


var query = list1.Where(l1 => list2.Any(l2=> l2.g4 == l1.g2));
like image 32
arunlalam Avatar answered Oct 20 '22 02:10

arunlalam


How about this:

var results = 
    from a in list1
    join b in list2 on a.g2 equals b.g4
    select a;

This will return all items from list1 where there exists an item in list2 with the MyObject1.g2 == MyObject2.g4.

like image 24
p.s.w.g Avatar answered Oct 20 '22 04:10

p.s.w.g