C# 如何计算 LINQ 中 DataTable 列的总和(到数据集)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/550187/
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-04 07:47:48  来源:igfitidea点击:

How to calculate sum of a DataTable's Column in LINQ (to Dataset)?

c#linqdatatablesum

提问by rivera.reyrivera

I'm just started to read up on LINQ and I want to start incorporating it into my code. I know how to compute the sum of a DataTable's column by either "Foreach"-ing through the rows or by doing a compute.sum on the specific column. How do I do the equivalent with LINQ to DataSet?

我刚刚开始阅读 LINQ,我想开始将它合并到我的代码中。我知道如何通过“Foreach”遍历行或在特定列上执行 compute.sum 来计算 DataTable 列的总和。如何使用 LINQ to DataSet 执行等效操作?

采纳答案by Marc Gravell

If untyped (replace intwith the correct data type):

如果无类型(替换int为正确的数据类型):

 var sum = table.AsEnumerable().Sum(x=>x.Field<int>(3));

or:

或者:

 var sum = table.AsEnumerable().Sum(x=>x.Field<int>("SomeProperty"));

If typed:

如果输入:

 var sum = table.Sum(x=>x.SomeProperty);

回答by Siddhartha

If you data field is integer

如果您的数据字段是整数

var sum = TableData.Sum(x => x.FieldName);

If your data field is string then you need to parse it as integer

如果您的数据字段是字符串,那么您需要将其解析为整数

var sum = TableData.Sum(x => Int32.Parse(x.FieldName));

If your data field is string and you want to store result as string

如果您的数据字段是字符串并且您想将结果存储为字符串

var sum = TableData.Sum(x => Int32.Parse(x.FieldName)).ToString();