c# - How to write Linq expression using external objects -
i trying convert loop in linq expression. seams not work way doing it:
var customer = getcustomerfromdatabase(id); icollection<order> customerorders = null; if (customer == null) { logandthrowcustomernotfound(id); } else { customerorders = customer.orders; } customer.yeartodatesales = 0.0; customer.currentsales = 0.0; datetime today = datetime.now; if (customerorders != null) foreach (var order in customerorders) { if (order.submitteddate != null && order.submitteddate.value.year.compareto(today.year) == 0) { customer.yeartodatesales += (double)order.ordertotal; } if (order.submitteddate != null && (order.submitteddate.value.month.compareto(today.month) == 0 && order.submitteddate.value.year.compareto(today.year) == 0)) { customer.currentsales += (double)order.ordertotal; } }
so came expression customer orders match current year... bot not work. in expression order empty , today conflicting. i create datetime today = datetime.now; in parm of expression different errors...
ienumerable<order> corders = customerorders .where((icollection<order> order , today) => order.submitteddate.value.month == today.month);
it's simpler if don't attempt pass today
lambda, it'll closed expression anyway;
customer.yeartodatesales = customerorders .where(x => x.submitteddate != null && x.submitteddate.value.year == today.year) .sum(x => x.ordertotal); customer.currentsales = customerorders .where(x => x.submitteddate != null && x.submitteddate.value.month == today.month && x.submitteddate.value.year == today.year) .sum(x => x.ordertotal);
Comments
Post a Comment