1

我有两个清单:

一种。要求的设施
湾。有设施的单位。

我想过滤那些具有任何一种“要求的便利设施”的单位。我尝试使用foreach循环来实现相同的结果,但我相信使用 LINQ 应该更容易。有人可以帮忙\建议吗?

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

3 回答 3

1

您可以根据是否符合 Intersect 规则进行过滤

var matchedAmenities = ExactMatchApartments.Where(ema => ema.Amenities
                                               .Any(x => unitSearchRequestAmenities
                                                   .Count(y => y.ID == x.ID) == 1));
exactMatchApartmentsFilteredByAmenities.AddRange(matchedAmenities);

Intersect鉴于默认的 LINQIntersect扩展不支持 lambda 表达式,这有点“自定义” 。

于 2012-06-12T03:59:45.523 回答
0

很难从您的类型中分辨出来,但我认为以下内容应该可以解决问题

from unit in ExactMatchApartments
from amenity in unit.Amenities
join requestedAmenity in unitSearchRequestAmenities
on amenity.ID equals requestedAmenity.ID
select unit

在这种情况下,查询表达式比点表示法更易于阅读和理解。

于 2012-06-12T03:49:37.220 回答
0

谢谢杰森,我相信它一定是相交而不是例外。我已将代码更改为以下内容:

var amenities = unitSearchRequest.Amenities;
if (amenities.Count > 0)
{
    //filter the unit's amenities's id's with the search request amenities's ID's.
    var exactMatchApartmentsFilteredByAmenities= new Units();
    var requestAmenitiesIds = amenities.Select(element => element.ID);
    foreach (var unitCounter in ExactMatchApartments)
    {
        var unitAmenities = unitCounter.Amenities.Select(element => element.ID);
        var intersect    =unitAmenities.Intersect(requestAmenitiesIds);
        if (intersect.Any())
        {
            exactMatchApartmentsFilteredByAmenities.Add(unitCounter);
            break;
        }
    }
}    

我将测试代码并在此处更新我的结果。

于 2012-06-12T04:04:11.213 回答