使用LINQ过滤2个列表

时间:2012-06-12 03:36:42

标签: c# .net linq

我有两个清单:

a. requestedAmenities 
b. units with amenities. 

我想过滤那些有“任务设施”的单位。 我试图使用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
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以根据符合相交规则

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

这是一个有点“自定义”Intersect,因为默认的LINQ Intersect扩展名不支持lambda表达式。

答案 1 :(得分:0)

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

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

与点符号相比,这种情况下查询表达式更容易阅读和理解。

答案 2 :(得分:0)

感谢Jason,我相信它必须是Intersect而不是Except。我已将代码更改为以下内容:

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

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