Filter across 2 lists using LINQ
- by Ajit Goel
I have two lists:
a. requestedAmenities
b. units with amenities.
I want to filter those units that have any one of the "requested amenities".
I have tried to achieve the same result using foreach loops but I believe it should be much easier using LINQ. Can someone please help\advice?
UnitAmenities unitSearchRequestAmenities = unitSearchRequest.Amenities;
var exactMatchApartmentsFilteredByAmenities= new Units();
IEnumerable<string> requestAmenitiesIds = unitSearchRequestAmenities.Select(element => element.ID);
foreach (var unitCounter in ExactMatchApartments)
{
IEnumerable<string> unitAmenities = unitCounter.Amenities.Select(element => element.ID);
foreach (var requestAmenityId in requestAmenitiesIds)
{
foreach (var unitAmenity in unitAmenities)
{
if (requestAmenityId == unitAmenity)
{
exactMatchApartmentsFilteredByAmenities.Add(unitCounter);
//break to the outmost foreach loop
}
}
}
}