2015-10-20 24 views
1

我有以下選擇:條件數學

q.Select(c => new SomeObject 
    { 
     Invoices = c.SomeList.Sum(sl => sl.SomeValue), 
     Payments = c.OtherList.Sum(ol => ol.OtherValue), 
     Balance = ??? // Should be Payments - Invoices 
    }); 

我想計算,並與對象的其餘部分一起返回平衡,但無法弄清楚如何做到這裏面的select語句。謝謝!

+1

你可以做到這一點... q.Select(C => new SomeObject Balance = c.OtherList.Sum(ol => ol.OtherValue)-c.OtherList.Sum(ol => ol.OtherValue) }); – Dragon

+0

讓'SomeObject'建立起來。給它一個構造函數:'q.Select(c => new SomeObject(c));' – Jonesopolis

+0

你不能做'Balance = c.OtherList.Sum(o1 => o1.OtherValue) - c.SomeList.Sum s1 => s1.SomeValue)'? – singsuyash

回答

6

無需匿名類型也多次迭代。只需將您的Select表達式轉換爲代碼塊,然後使用局部變量。

q.Select(c => 
       { 
        var invoices = c.SomeList.Sum(sl => sl.SomeValue); 
        var payments = c.OtherList.Sum(ol => ol.OtherValue); 
        // do stuff 
        return new SomeObject 
        { 
         Invoices = invoices, 
         Payments = payments, 
         Balance = payments - invoices 
        }; 
       }); 

由於@juharr建議,你也可以讓Balance只讀屬性,返回Payments - Invoices。如果Balance不需要設置,這是建議的方法。

+0

如果這是EF查詢,這將不起作用。 – Servy

+0

來自@juharr的評論和您的答案都很有用,謝謝!不幸的是,對Stackoverflow我沒有足夠的觀點來支持juharr的評論。 – Alex

+1

我向你提出了@ juharr的評論;) – Tom

3

您可以引入一個匿名類型來保存中間計算,然後從這種類型的創建SomeObject

q.Select(c => new 
       { Invoices = c.SomeList.Sum(sl => sl.SomeValue), 
       Payments = c.OtherList.Sum(ol => ol.OtherValue) 
       } 
).Select(x => new SomeObject 
       { Invoices = x.Invoices, 
       Payments = x.Payments, 
       Balance = x.Payments - x.Invoices 
       }); 
-1

無法裏面你需要一個第二選擇做選擇

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<SomeObject> q = new List<SomeObject>(); 

      q.Select(c => new 
      { 
       Invoices = c.SomeList.Sum(), 
       Payments = c.OtherList.Sum(), 

      }).Select(x => x.Payments - x.Invoices); 

     } 
    } 
    public class SomeObject 
    { 
     public int[] SomeList { get; set; } 
     public int[] OtherList { get; set; } 
    } 
}​ 
+1

它可以在'Select'內完成。此外,這不會返回SomeObject的Enumerable。相反,它將返回任何數據類型Payments/Invoices的Enumerable。 – Tom

+0

借調。這不是一個正確的答案。 – Kapol

0

您還可以使用let條款:

var query= from e in q 
      let invoices= e.SomeList.Sum(sl => sl.SomeValue); 
      let payments = e.OtherList.Sum(ol => ol.OtherValue); 
      select new SomeObject 
         { 
         Invoices = invoices, 
         Payments = payments, 
         Balance = payments - invoices 
         };