LINQ-以字符串形式存储的数字总和 [英] LINQ - Sum of numbers stored as string
本文介绍了LINQ-以字符串形式存储的数字总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
名称价格
ABC
B CBA
C 20
D 22
F 12
G 32
H 12
数据表将获得thease值,但我想获得Price列的总和.当字符串值将出现在行中时,它将被视为0,请为此提供解决方案.
谢谢,
Amod Kumar
Name Price
A ABC
B CBA
C 20
D 22
F 12
G 32
H 12
datatable will get thease value but i want to get the sum of Price column.when ever string value will be in row, It would be consider as a 0, Please provide solution for this.
Thanks,
Amod Kumar
推荐答案
以下LINQ语句对可以转换为int
的值进行求和:
The following LINQ statement sums the values that can be converted into anint
:
DataTable dt = ...
...
string col = "Price";
int sum = dt.AsEnumerable()
.Aggregate(0,(n, r)=>
{
int v;
return int.TryParse((r[col] as string) ?? string.Empty, out v)
? n + v
: n;
}
);
或者更容易阅读:
Or a bit easier to read:
DataTable dt = ...
...
int sum = dt.AsEnumerable().Aggregate(0,(n,r)=>PriceField(r)+n);
...
static int PriceField(DataRow r)
{
int v;
return int.TryParse((r["Price"] as string) ?? string.Empty, out v) ? v : 0;
}
或其他替代方法:
Or a further alternative:
DataTable dt = ...
...
int sum = dt.AsEnumerable().Aggregate(0,SumPriceField);
...
static int SumPriceField(int n, DataRow r)
{
int v;
return int.TryParse((r["Price"] as string) ?? string.Empty, out v) ? n + v : n;
}
干杯
Andi
Cheers
Andi
double SgAmount = (from DataRow row in dt.Rows
where Double.TryParse(row.Field<string>("Test"), out total_SG) == true
select total_SG).Sum();
下面是完整的,经过测试的示例代码.
The following is the complete working and tested sample code.
public static void main()
{
DataTable dt = new DataTable();
dt.Columns.Add("Price");
var dr = dt.NewRow();
dr["Price"] = "12";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Price"] = "A1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Price"] = "1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Price"] = "2";
dt.Rows.Add(dr);
var sum = (from datarow in dt.AsEnumerable()
where (Program.NullableTryParseInt32(datarow["Price"].ToString()) != null)
select datarow["Price"]).ToArray().Sum(x => Convert.ToInt32(x));
}
public static int? NullableTryParseInt32(string text)
{
int value;
return int.TryParse(text, out value) ? (int?)value : null;
}
让我知道这是否解决了您的问题.
let me know whether this solved your problem.
这篇关于LINQ-以字符串形式存储的数字总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文