Linq: selecting a collection of properties

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 am using Nhibernate Linq. If I want to get the total amount of order filters from 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 free syntax?

+2
source share
1 answer

Try the following:

 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 selected orders, 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; 
0
source

Source: https://habr.com/ru/post/951284/


All Articles