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
CodePudding user response:
Try this out, It will work now.
MyContext.ListOfEntityA.Where(a => ListOfEntityB.Exists(b => b.Property.Value == a.Property.Value));
CodePudding user response:
ListOfEntityA.Where(a => ListOfEntityB.Any(b => b.Property == a.Property))
CodePudding user response:
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 });