Vincent
Vincent

Reputation: 1151

How do I convert this expression to LINQ?

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

Answers (3)

timeshift
timeshift

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

Nekresh
Nekresh

Reputation: 2988

termsOfPayment = (
                   from g in _customer.CustomerGroups
                   where g.TermsOfPayment != null
                   orderby g.TermsOfPayment.InvoiceDueDays
                   select g.TermsOfPayment
                 ).FirstOrDefault();

Upvotes: 3

oleveau
oleveau

Reputation: 198

     var termsOfPayment =
        _customer.CustomerGroups.OrderBy(cg=>cg.TermsOfPayment.InvoiceDueDays)
        .First().Select(cg=>cg.TermsOfPayment);

Upvotes: 1

Related Questions