Linq: select property collection

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-04 13:47:08

问题


I have two classes:

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

I use Nhibernate Linq. If I want to get total sum of orders filtering by Persan.Name I do this:

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

How can I do the same using fluent syntax?


回答1:


Try this:

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

If this solution throws an ArgumentNullException when there are no orders selected try this two step solution:

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


来源:https://stackoverflow.com/questions/13171394/linq-select-property-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!