How to set round of the result of aggregate functi

2019-09-05 01:49发布

问题:

Below is my code:

sFieldList.Select(y => "Sum(Convert.ToDouble(iif(it[\""+y+"\"] == @0,0,it[\""+y+"\"]))) as "+y)and then 

var newSort = dataTable
                .AsEnumerable()
                .AsQueryable()
                .GroupBy("new("+gField+")", "it")
                .Select("new("+sField+",it.Key as Key, it as Data)",DBNull.Value);

I wish to round of the result of Sum() method above to 2 decimal digits. How can I add it in this query itself?

回答1:

Hopefully I'm understanding your problem correctly, but as far as I can tell, you just need an additional Select()

    var roundedSums = list.Select(x => "some dynamic query on x")
                          .Select(x => Math.Round(x, 2);

By chaining multiple Selects(), you are simply projecting your original set on a record to record basis.

If this isn't what you're looking for, we may need a bit more clarification.



回答2:

Somehow dynamic linq does not always understand the numbers in terms of their, so try this:

sFieldList.Select(y => "Sum(Math.Round(Convert.ToDouble(iif(it[\""+y+"\"] == @0,0,it[\""+y+"\"])),@1)) as "+y)

and then

var newSort = dataTable
            .AsEnumerable()
            .AsQueryable()
            .GroupBy("new("+gField+")", "it")
            .Select("new("+sField+",it.Key as Key, it as Data)",DBNull.Value,2);