Linq select where entity property value matches value of property of any item in another List

Viewed 946

Using Linq in C#, how do I select items from an list of objects of one entity type, where the value of a property of any of the objects matches the value of a property of any object in in a list containing objects of a different entity type? I'm looking for a real expression using fluent syntax that performs the function of the following Pseudocode (Entity A and Entity B aren't linked by keys)

MyContext.ListOfEntityA.Where(a => ListOfEntityB.Contains(ListOfEntityB.Property.Value == a.Value))

To clarify, if the collections contain objects that look like this:

ListOfEntityA
-------------
EntityA_Object.Property = 1
EntityA_Object.Property = 2

ListOfEntityB
-------------
EntityB_Object.Property = 2

Then the expression should return the 2nd item in ListOfEntityA

3 Answers

Try this out, It will work now.

MyContext.ListOfEntityA.Where(a => ListOfEntityB.Exists(b => b.Property.Value == a.Property.Value));
ListOfEntityA.Where(a => ListOfEntityB.Any(b => b.Property == a.Property))

Any checks whether there is a match with an item in ListOfEntityB or not, and Where returns the objects in ListOfEntityA for which a match was found. See live:

https://dotnetfiddle.net/rbOJg5

You could use a LINQ join expression to join the two lists on the matching property, filtering out all the elements without matching results.The result should be the matching elements from both lists as an IEnumerable result.

ListOfEntityA
.Join(ListOfEntityB, l => l.Property, r => r.Property, (a, b) => new { EntityAObject = a, EntityBObject = b });
Related