2011-02-25 61 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;