如何使用LINQ过滤子集合的属性(.Any())

时间:2009-05-01 03:19:04

标签: linq nhibernate

如何在LINQ中执行以下SQL?我实际上正在使用LINQ到NHibernate(但是由于我认为嵌入式lambda表达式,它可能在NHibernate LINQ中不可能)。但我想知道如何在LINQ中做到这一点。我以前从未遇到过这种情况。

SELECT c.CustomerID, c.CustomerName --etc
FROM   Customers c
       INNER JOIN Orders o
         ON c.CustomerID = o.CustomerID
WHERE  o.Status = 1

public class Customer
{
  public int CustomerID { get; set; }
  public string CustomerName { get; set; }  
  public IList<Order> Orders { get; set; }
}

public class Order
{
  public int OrderID { get; set; }
  public int CustomerID { get; set; }
}

我想做类似的事情:

var customers = 
    (from c in Customers
    where c.Orders.Where(o => o.Status == 1)
    select c).ToList();

谢谢!

3 个答案:

答案 0 :(得分:11)

where语句返回一个集合。你想使用Any()方法

var customers = from c in Customers
                where c.Orders.Any(o => o.Status = 1)
                select c

答案 1 :(得分:0)

此解决方案要求LINQ在订单和客户之间存在关系(即客户有订单属性),但您可以使用:

  var customers = 
        (From c in Customers, o In c.Orders
        Where o.Status == 1 
        Select c).ToList()

干杯!

答案 2 :(得分:0)

您是在寻找LAMBDA还是直接LINQ to SQL?你只是想加入吗?

这是使用lambda的连接:

var lambda =
Customers.Join (
    Orders,
    c => c.CustomerID,
    o => o.CustomerID,
    (c, o) => new { c, o }
)
.Where  (w => w.o.Status == 1)
.Select (s => s.c.CustomerID, s.c.CustomerName);