Filter across 2 lists using LINQ

Posted by Ajit Goel on Stack Overflow See other posts from Stack Overflow or by Ajit Goel
Published on 2012-06-12T03:36:42Z Indexed on 2012/06/12 4:40 UTC
Read the original article Hit count: 216

Filed under:
|
|

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
            }
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET