2011-02-25 58 views
1

是否有可能将此表达式转换为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表达式,并很渴望lern更多 - 因此这个职位的原因。

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

回答

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

您好,我认为您的解决方案是优雅。我不确定你的表情或者@Steven给出的表情是否更有效率,但是不管怎样,不会有很多小组进行排序。如果通过用“grp”,“g”或其他(“group”无效)替换“group”来更新答案并添加“select g.TermsOfPayment”到最后,我会将您的答复标记为已回答。 – Vincent 2011-02-25 10:30:35

+0

@Vincent:对保留字抱歉,现在已更正 – Nekresh 2011-02-25 11:04:10

+0

@Vincent:将速度与其他实现进行比较可能很有趣。 OrderBy'需要在排序之前完全消耗枚举。一旦完成,它将允许我们使用已排序的枚举。它以两遍完成,但我认为它更好地描述了行为。 – Nekresh 2011-02-25 11:09:35

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

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

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