Reputation: 1151
Is it possible to convert this expression to LINQ?
TermsOfPayment termsOfPayment = null;
foreach (CustomerGroup group in _customer.CustomerGroups)
if (termsOfPayment == null) termsOfPayment = group.TermsOfPayment;
else if (group.TermsOfPayment != null)
if (group.TermsOfPayment.InvoiceDueDays < termsOfPayment.InvoiceDueDays)
termsOfPayment = group.TermsOfPayment;
It might seem like a stupid question since the expression above solves the question, but I use some LINQ expressions and am eager to lern more - hence the reason for this post.
Basically I just want to select the TermsOfPayment object with the minimum InvoiceDueDays (integer) value from the groups the customer is a part of.
Upvotes: 1
Views: 111
Reputation: 255
Why not use aggregate, speed is better too:
var termsOfPayment =
_customer.CustomerGroups.Aggregate((a, n) => n.TermsOfPayment.InvoiceDueDays < a.TermsOfPayment.InvoiceDueDays ? n : a).TermsOfPayment;
Upvotes: 0
Reputation: 2988
termsOfPayment = (
from g in _customer.CustomerGroups
where g.TermsOfPayment != null
orderby g.TermsOfPayment.InvoiceDueDays
select g.TermsOfPayment
).FirstOrDefault();
Upvotes: 3
Reputation: 198
var termsOfPayment =
_customer.CustomerGroups.OrderBy(cg=>cg.TermsOfPayment.InvoiceDueDays)
.First().Select(cg=>cg.TermsOfPayment);
Upvotes: 1