0

私は2つのテーブルを持ってい
  ます1.クライアント
  2.操作

操作の結果: クレジットまたはデビット (文字フィールドの「C」または「D」) と、日付および金額フィールド。

linQ を使用して各クライアントのアカウントの残高を計算する必要があります...結果には、まだ操作を行っていないクライアントの残高も 0 と表示されるはずです

私はlinQステートメントで次の関数を持っていますが、より良く、より速く、より短い方法で実行できることを知っていますよね? どっちが?

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());
}

ありがとう !!!

4

1 に答える 1

0

LINQ-to-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 メソッドは 0 を返すため、トランザクションのないクライアントを処理します。

編集:
クエリのスペルを修正:Ampont -> Amount

于 2009-11-08T05:21:01.657 に答える