none
Add all values in a specified column RRS feed

  • Question

  • Hi,

    I wondering if anyone knows how to add all of the values in a specific column so you can output the sum

    for example: int x = sum of Column_Abc...

    Thanks,

    Kevind
    Sunday, August 9, 2009 5:40 PM

Answers

  • One way to do this is to use a separate column with an expression:

            static void Main(string[] args)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("ints", typeof(int));
                dt.Columns.Add("total", typeof(int), "SUM(ints)");
    
                dt.Rows.Add(new object[] { 10 });
                dt.Rows.Add(new object[] { 20 });
                dt.Rows.Add(new object[] { 30 });
                dt.Rows.Add(new object[] { 40 });
    
                Console.WriteLine("Total: {0}", dt.Rows[0]["total"].ToString());
            }



    Note that this will add a column to each row.I have not tested for performance, but perhaps this is usable for you.

    HTH
    //Michael


    This posting is provided "AS IS" with no warranties.
    Monday, August 10, 2009 7:45 AM

All replies

  • One way to do this is to use a separate column with an expression:

            static void Main(string[] args)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("ints", typeof(int));
                dt.Columns.Add("total", typeof(int), "SUM(ints)");
    
                dt.Rows.Add(new object[] { 10 });
                dt.Rows.Add(new object[] { 20 });
                dt.Rows.Add(new object[] { 30 });
                dt.Rows.Add(new object[] { 40 });
    
                Console.WriteLine("Total: {0}", dt.Rows[0]["total"].ToString());
            }



    Note that this will add a column to each row.I have not tested for performance, but perhaps this is usable for you.

    HTH
    //Michael


    This posting is provided "AS IS" with no warranties.
    Monday, August 10, 2009 7:45 AM
  • Michael,
     
    Thanks for the reply but i am very new to this and would appreciate if you could explain that code.

    Thanks,

    Kevin
    Monday, August 10, 2009 1:19 PM
  • The following line of code from Michael's post
       dt.Columns.Add("total", typeof(int), "SUM(ints)");
    is the key. It creates a column that uses an expression language that DataSet has to create calculated values.

    Sum is a operator in the language and ints is a column that is specified that will be summed.

    Thanks
    Chris Robinson
    Program Manager - DataSet


    This posting is provided "AS IS" with no warranties, and confers no rights.
    Monday, August 10, 2009 9:41 PM