2009-11-08 66 views
0

我有2個表
  1.客戶
  2.操作使用LINQ簡單的數學問題,簡單的聯接查詢,空值等

操作可導致:現金或借記( 'C' 或' D'在char字段中)以及日期和安裝字段。

我必須計算使用LINQ ......結果也應顯示爲客戶誰沒有做業務尚未

我有一個LINQ聲明如下功能平衡0每個客戶的賬戶中的餘額,但我知道它可以以更好,更快,更短的方式完成,對吧?哪個會?

public static double getBalance(ref ClasesDeDatosDataContext xDC, string SSN, 
int xidClient) 
{ 
    var cDebits = 
     from ops in xDC.Operations 
       where (ops.idClient == xidClient) && (ops.OperationCode == 'D') 
       select ops.Ammount; 
    var cCredits = 
       from ops in xDC.Operations 
       where (ops.idClient == xidClient) && (ops.OperationCode == 'C') 
       select ops.Ammount; 
    return (double)(cCredits.Sum() - cDebits.Sum()); 
} 

謝謝!

回答

0

我不知道,如果LINQ到SQL引擎可以處理的表達,但這樣的事情應該是可能的:

return (
    from ops in xDC.Operations 
    where ops.idClient == xidClient 
    select ops.operationCode == 'C' ? ops.Amount : -ops.Amount 
).Sum(a => a); 

或許:

return (
    from ops in xDC.Operations 
    where ops.idClient == xidClient 
    select new { Sign = ops.operationCode == 'C' ? 1.0 : -1.0, Amount = ops.Amount } 
).Sum(o => o.Sign * o.Amount); 

如果集合是空的,Sum方法返回零,以便在沒有交易的情況下照顧客戶。

編輯:
更正查詢拼寫:Ampont - >金額

+0

我得到一個運行時異常...空值不能分配給具有類型System.Double的成員這是一個非空的值類型。 – Enrique 2009-11-08 20:23:30

+0

他們哪一個?金額字段可以爲空嗎?除了'C'或'D'還有其他的操作嗎? – Guffa 2009-11-08 21:50:54

+0

嗨Guffa ...檢查截圖。這是在運行時的例外(一些信息是西班牙語)... http://img130.imageshack.us/i/sshot1s.jpg/ – Enrique 2009-11-10 11:28:12