2009-11-08 69 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