I have two Generic Lists containing different types, for the sake of example, lets call them Products
and Employees
. I'm trying to find Products that are based at the same location as Employees, i.e. where product.SiteId == emp.SiteId
List<Product> lstProds;
List<Employees> lstEmps;
My (old skool) brain is telling me to use a forEach
loop to find the matches but I suspect there is a ('better'/terser/faster?) way to do it using Linq. Can anyone illuminate me? All the examples I've found online deal with Lists of primitives (strings/ints) and are not especially helpful.
I would say:
However, if there are multiple employees with the same site ID, you'll get the products multiple times. You could use
Distinct
to fix this, or build a set of site IDs:That's assuming
SiteId
is anint
- if it's an anonymous type or something similar, you may want an extra extension method:Then:
Alternatively, if you have few employees, this will work but is relatively slow:
Add a
ToList
call to any of these approaches to get aList<Product>
instead of anIEnumerable<Product>
.