Add Datatable C# columns with Linq

Asked

Viewed 1,633 times

1

I have a DataTable containing a column called SubTotal. I would like to add up the total value of this column.

I tested some examples:

object sumObject;
sumObject = table.Compute("Sum(Amount)", "");

This one too:

this.LabelControl.Text = datatable.AsEnumerable()
.Sum( x => x.Field<int>( "Amount" ) )
.ToString();

But they didn’t work. How to do this?

  • That’s it, you need to figure out what you’re doing wrong, but since you didn’t post a [mcve] it’s complicated for us to help.

1 answer

2


Nothing wrong, you should check if the Datatable is filled correctly. Follow an example to help.

        //cria DataTable
        var dt = new DataTable("teste");
        dt.Columns.Add("valor", typeof(decimal));

        //cria valores teste
        for (int i = 1; i <= 5; i++)
        {
            var r = dt.NewRow();
            r["valor"] = i;
            dt.Rows.Add(r);
        }

        //Faz a soma via Linq
        var mostrar = dt
            .AsEnumerable()
            .Sum(s => s.Field<decimal>("valor"))
            .ToString();

        MessageBox.Show(mostrar);
  • Man, thanks, my mistake was juxtaposing on the field guy. It was filled correctly the datatable however it was making confusion with the field type.

  • Very useful this last part of the code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.