C# 使用 linq to sql 求和列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1744673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:25:21  来源:igfitidea点击:

sum column with linq to sql

c#linq-to-sql

提问by Rod

I have a DataView in which I would like to sum a column called "Amount"

我有一个 DataView,我想在其中对名为“Amount”的列求和

Now I know I can iterate thru the columns and get the sum but I was wondering if is possible using Linq to Sql?

现在我知道我可以遍历列并获得总和,但我想知道是否可以使用 Linq to Sql?

String sum = Linq to Sql stuff here (doesn't have to be a string, can be any type)

String sum = Linq to Sql 这里的东西(不一定是字符串,可以是任何类型)

Thanks, rodchar

谢谢,罗德查尔

采纳答案by Justin Niessner

Assuming the Amount column is a double (could be another type)

假设金额列是双精度(可能是另一种类型)

double sum = Table.Select(t => t.Amount ?? 0).Sum();

Or

或者

double sum = Table.Sum(t => t.Amount ?? 0).Sum();

Using the null coelescing operator will give you a default of 0 if t.Amount is null.

如果 t.Amount 为空,则使用空合并运算符将为您提供默认值 0。

回答by queen3

Excuse me for dataContext call syntax...

请原谅我的 dataContext 调用语法...

var sum = dataContext.Sum(x => x.Amount);

If you want to sum strings, you may want to use

如果您想对字符串求和,您可能需要使用

var sum = string.Join(", ", dataContext.Select(x => x.StringColumn).ToArray());

Hope this works.

希望这有效。