如何将此表达式转换为LINQ?

时间:2011-02-25 09:56:36

标签: c# linq

是否可以将此表达式转换为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;

这可能看起来像一个愚蠢的问题,因为上面的表达式解决了这个问题,但是我使用了一些LINQ表达式并且渴望更多 - 因此这篇文章的原因。

基本上我只想从客户所属的组中选择具有最小InvoiceDueDays(整数)值的TermsOfPayment对象。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

为什么不使用聚合,速度也更好:

var termsOfPayment = 
    _customer.CustomerGroups.Aggregate((a, n) => n.TermsOfPayment.InvoiceDueDays < a.TermsOfPayment.InvoiceDueDays ? n : a).TermsOfPayment;