Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

c# - Invalid usage of aggregate function Sum() and Type: String

I have a data table and a column contains int values. I have not specified the column with any datatype. When I perform the following.

object sum = dttest.Compute("sum(Value)", "");

I am getting below error.

Invalid usage of aggregate function Sum() and Type: String.

And I tried converting column value to int using

object sum = dttest.Compute("sum(Convert(Value, 'System.Int32'))","");

again I am getting another error

Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier.

When I specify the datatype for the column, first code will return correct value. But in my case I can't specify column datatype. Any one having solution ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use LINQ to Datatable:

 var result = dttest.AsEnumerable()
                    .Sum(x => Convert.ToInt32(x["Value"]));

Example how to Sum for specific name:

 var result = dttest.AsEnumerable()
                    .Where(r => r.Field<string>("Name") == "FilterName")
                    .Sum(x => Convert.ToInt32(x["Value"]));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...