Adding C # DataTable columns with Linq

1

I have a DataTable that contains a column named SubTotal . I would like to add the total value of this column.

I tested some examples:

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

This too:

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

But they did not work. How to do this?

    
asked by anonymous 15.02.2017 / 21:08

1 answer

2

Nothing wrong, you should check if the DataTable is filled correctly. Here's 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);
    
16.02.2017 / 03:11