Linq:选择属性集合

时间:2012-11-01 05:22:28

标签: linq fluent-nhibernate linq-to-nhibernate

我有两个班级:

public class Person
{
   public int Id{get;set;}
   public string Name{get;set;}
   public List<Order> Orders{get;set;}
}
public class Order
{
   public int Id{get;set;}
   public string Data{get;set;}
   public decimal Sum{get;set;}
}

我使用Nhibernate Linq。如果我想通过Persan.Name过滤订单的总和,我会这样做:

var result = (from person in personRepository.Query
             from order in person.Orders
             where person.Name.Contains("off")
             select order).Sum(order => order.Sum);

如何使用流利的语法执行相同的操作?

1 个答案:

答案 0 :(得分:0)

试试这个:

var result = personRepository.Query
    .Where(person => person.Name.Contains("off"))
    .SelectMany(person => person.Orders)
    .Sum(order => order.Sum);

如果此解决方案在没有选择订单时抛出ArgumentNullException,请尝试以下两步解决方案:

var orders = personRepository.Query
    .Where(person => person.Name.Contains("off"))
    .SelectMany(person => person.Orders);
var result = orders.Any()
    : orders.Sum(order => order.Sum)
    ? 0;