简体   繁体   English

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

[英]How do I convert this expression to LINQ?

Is it possible to convert this expression to 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;

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

Basically I just want to select the TermsOfPayment object with the minimum InvoiceDueDays (integer) value from the groups the customer is a part of. 基本上我只想从客户所属的组中选择具有最小InvoiceDueDays(整数)值的TermsOfPayment对象。

termsOfPayment = (
                   from g in _customer.CustomerGroups
                   where g.TermsOfPayment != null
                   orderby g.TermsOfPayment.InvoiceDueDays
                   select g.TermsOfPayment
                 ).FirstOrDefault();
     var termsOfPayment =
        _customer.CustomerGroups.OrderBy(cg=>cg.TermsOfPayment.InvoiceDueDays)
        .First().Select(cg=>cg.TermsOfPayment);

Why not use aggregate, speed is better too: 为什么不使用聚合,速度也更好:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM