0

## C# lambda Sum and Divide

deh 2021-03-23 10:26:41588 瀏覽

``````var sumA = table.Sum(s => s.columnA);
var sumB = table.Sum(s => s.columnB);
var target = sumA/sumB;
``````

### 1 個回答

4
japhenchen
iT邦大師 1 級 ‧ 2021-03-23 10:48:03

``````var target = table.Sum(s => s.columnA/s.columnB) ;
``````

``````try{
var target = table.Sum(s => s.columnA/s.columnB) ;
}
catch(Except ex){
Console.WriteLine(ex.Message);
}
``````
YoChen iT邦研究生 3 級 ‧ 2021-03-23 11:03:24 檢舉

`(A1+B1+C1) / (A2+B2+C2) != A1/A2 + B1/B2 + C1/C2`

lambda是each的委派沒錯吧？

``````var sum = 0;
foreach(var row in table){
s += row.A / row.B;
}

``````

deh iT邦新手 2 級 ‧ 2021-03-23 11:31:27 檢舉

sum(s=>s.a/s.b)是上述那樣沒錯

``````var sA = 0;
var sB = 0;
foreach(var row in table){
sA += row.A;
sB += row.B;
}
var target = sA/sB;
//這樣的結果跟sum(s=>s.a/s.b)不同
``````

``````double target = (double)(table.Sum(s => s.columnA) / table.Sum(s => s.columnB));
``````

``````Row1 : A 12   B 3  A/B = 4
Row2 : A 10  B 5  A/B = 2
Row3 : A 24  B 4  A/B = 6

SUM(Row1:Row3) = 12
SUM(A) / SUM(B) = 46 / 12 = 3.8333
(total Average)?
``````
YoChen iT邦研究生 3 級 ‧ 2021-03-23 12:19:17 檢舉

``````var target = table.Sum(s => s.columnA) / table.Sum(s => s.columnB)
``````

``````var target = (double)table.Sum(s => s.columnA) / (double)table.Sum(s => s.columnB)
``````