c# - Convert foreach in a single query -


i have linq query , loop inside like:

double total = 0;  ienumerable<dispatch> requireddispatches = dispatches.where(x => x.orderid == selectedorder.orderid); foreach(dispatch dispatch in requireddispatches) {     total += dispatch.dispatchitemtransactions.sum(x => x.quantity); } 

i have tried half only:

total = dispatches.where(x => x.orderid == selectedorder.orderid)                   .select(x => x.dispatchitemtransactions).sum( x => x. 

but after x.it not give me property quantity.

you have flatten hierarchy first, use selectmany , sum

var total = dispatches.where(x => x.orderid == selectedorder.orderid)                       .selectmany(x => x.dispatchitemtransactions)                       .sum( x =>x.quantity);