简体   繁体   中英

How to calulate the grand total in c# by using a genertic type?

I am trying to write an application that will allow me to generate dynamic queries against my database. So far, I am able to generate/execute queries and populate the data into a table with no issues.

Now, some of my queries use SQL aggregate functions ie COUNT(*), SUM(), AVG(), MAX...

When I use aggregate columns, I need to be able to sum the aggregate column for the grand total. Since this is a dynamic query the data type could vary. It could be integer, double, or big integer

After the query is executed, I populate the data into a list of dictionary. My list is defined like this

public List<Dictionary<string, object>> Data { get; set; }

To populate the data into HTML table with no grand total I do the following in my view

@for (int y = 0; y < Model.Data.Count; y++)
{
    <tr>
        @foreach (var attribute in Model.Data[y])
        {
            <td>@attribute.Value</td>            
        }
    </tr>
}

Now, I need to be able to add grand total for some of the aggregate columns. But the problem is that I don't know the data type as it comes as a string.

Here is what I tried to do

@{

    var aggregateColumns = Model.Columns.Where(x => x.AggregateFunction != ReportsEngine.Support.ReportsGenerator.Report.Contracts.SqlAggregateFunctions.None).ToList();

    var grandTotals = new Dictionary<string, object>();
}

    @for (int y = 0; y < Model.Data.Count; y++)
    {
        <tr>
            @foreach (var attribute in Model.Data[y])
            {
                <td>@attribute.Value</td>

                var column = aggregateColumns.Where(x => x.SqlAlias == attribute.Key).FirstOrDefault();

                if(column != null)
                {
                    //At this point we know this is an aggregate column. Sum the data
                    //grandTotals[attribute.Key] += attribute.Value;
                }

            }
        </tr>
    }

As you can see I attempted to use a dictionary to increment each time. grandTotals[attribute.Key] += attribute.Value;

Is there a way to add the data up without knowing the actual data type?

How can I sum the columns in this case?

I need to be able to manually sum the records because I will later need to have sub totals based on the data.

This seems to work fine, although I am not all that comfortable with the approach:

var result = AddTypelessNumbers((int)15 , (decimal)15.12));


static dynamic AddTypelessNumbers(dynamic a, dynamic b)
{
    return a + b;    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM