Linq加入一对多AND Criteria

时间:2012-06-06 09:34:11

标签: linq join one-to-many

Product
+------------+-------------+------------+
| PID        | Name        | Model      |
+------------+-------------+------------+
|          1 | Mercedes    | xyz        |
|          2 | Audi        | yxz        |
|          3 | BMW         | zyx        |
+------------+-------------+------------+


ProductColor
+------------+-------------+------------+
| ID         | ProductID   | Color      |
+------------+-------------+------------+
|          1 | 1           | Red        |
|          2 | 1           | Blue       |
|          3 | 3           | Blue       |
+------------+-------------+------------+

我需要从ProductColor中选择ProductID,其中蓝色和红色?如何编写正确的Linq查询?

2 个答案:

答案 0 :(得分:0)

假设您在数据库表上有关系,那么这样的事情应该有效:

C#:

var ProductIDs = ctx.Products.Where(p => p.Color.Contains("Red") && 
    p.Color.Contains("Blue")).Select(p => p.PID)

VB:

Dim ProductIDs = ctx.Products.Where(function(p) p.Color.Contains("Red") And
    p.Color.Contains("Blue")).Select(function(p) p.PID)

答案 1 :(得分:0)

List<Product> Pr= data.Products.Where(x=> x.ProductColors.Where(y=>   
y.Color=="blue").Select(z=> z.ProductID).Contains(x.ID) && 
x.ProductColors.Where(y=> y.Color== "red").Select(z=> 
z.ProductID).Contains(x.ID)).ToList()

绿色

Ñ

如何进行多标准linq查询?