2012-11-01 100 views
2

我有兩個類:的LINQ:選擇屬性集合

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

我如何可以做同樣的用流利的語法?

回答

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; 
+0

謝謝!爲什麼應用程序拋出ArgumentNullException如果選定的訂單的計數是0? – mtkachenko

+0

請看我編輯的答案 – Spontifixus