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
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 };
var query = list1.Where(l1 => list2.Any(l2=> l2.g4 == l1.g2));
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With