简体   繁体   English

使用另一个列表的属性过滤对象列表。 使用linq

[英]Filter a list of objects using a property that is another list. Using linq

I've a nice situation, I think at beginning this a usual query but I'm having some problem trying to solve this, the situation is: 我有一个很好的情况,我认为在开始这是一个常见的查询,但我有一些问题试图解决这个问题,情况是:

I've a list of "Houses", and each house have a list of "Windows". 我有一个“房子”列表,每个房子都有一个“Windows”列表。 And I want to filter for a catalog only the Houses witch have a Blue windows, so my extension method of House is something like: 而且我想过滤一个目录,只有那个女巫有一个蓝色的窗户,所以我的扩展方法是这样的:

public static List<House> FilterByWindow (this IEnumerable<House> houses, Window blueOne){

    var list = houses.Select(p=>p.Windows.Where(q=>q.Color == blueOne.Color));
    return list.ToList();
}

Is this correct or I'm losing something? 这是正确的还是我失去了什么? Some better suggestion? 一些更好的建议?

If you want to search for House instances containing blue Windows , then use the existing Any extension: 如果要搜索包含蓝色Windows House实例,请使用现有的Any扩展:

var blueWindowHouses =
    from h in houses
    where h.Windows.Any(w => w.Color == blueOne.Color)
    select h;

What you have right now is not correct. 你现在拥有的是正确的。 The Select extension does not filter - it is a projection, and you aren't assigning the result to anything, so that line you have is effectively a no-op. Select扩展名不会过滤 - 它是一个投影,并且您没有将结果分配给任何内容,因此您拥有的行实际上是一个无操作。

Also, by wrapping this logic in a method, you can prevent the expression compiler from being able to translate it into a SQL statement. 此外,通过将此逻辑包装在方法中,可以防止表达式编译器将其转换为SQL语句。 Instead, write it all in one shot, as I have above, or accept and return an IQueryable<House> instead of accepting an IEnumerable<House> and returning a List<House> . 相反,如上所述,一次性写入,或接受并返回IQueryable<House>而不是接受IEnumerable<House>并返回List<House>

return houses.Where(house => house.Windows.Any(window => window.Color == blue))
             .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM