Perform a summation and save in session variable? asp.net

0

I am using session variables to save the data and the table, users, etc. (Then they travel to another page) and then I have the dilemma that I can not solve what steps to follow to make the summation of the Total label. I'm practically new with c # asp.net and I do not know much about coding. Thanks for any help.

Code that I used in the session of the table if it could be integrated (maybe take the data of the cell quantity while creating and multiplying, although I do not know what code would be in that case?)

if(Session["Dt"] == null)
    {
        DataTable Dt = new DataTable(); 
        Dt.Columns.Add("Sandwich");
        Dt.Columns.Add("Agregado");
        Dt.Columns.Add("Cantidad");

        Dt.Rows.Add(lista_sandwich.SelectedItem.Text, lista_agregado.SelectedItem.Text, caja_cantidad.Text); //Toma los campos del sandwich/agregado/cantidad (sus nombres y los une al row)
        tablita.DataSource = Dt;
        tablita.DataBind();
        Session["Dt"] = Dt;

        Session["cantidad"] = caja_cantidad.Text;
        label_suma.Text = Session["cantidad"].ToString();

    }
    else
    {
        DataTable Dt = Session["Dt"] as DataTable;
        Dt.Rows.Add(lista_sandwich.SelectedItem.Text, lista_agregado.SelectedItem.Text, caja_cantidad.Text); //Toma los campos del sandwich/agregado/cantidad (sus nombres y los une al row)
        tablita.DataSource = Dt;
        tablita.DataBind();
        Session["Dt"] = Dt;
    
asked by Sebastian Ismael 17.11.2018 в 04:42
source

1 answer

0

To calculate the total you could do something like this

int suma = 0;
foreach(var row in Dt){
  int cantidad = Convert.ToInt32(row["cantidad"]);
  suma += (cantidad  * 800) + (cantidad  * 200);
}

lblTotal.Text = suma.ToString();

Iteras each row of the datatable to make the addition, the other way would be using linq

int suma = Dt.AsEnumerable().Sum(r=> (r.Field<int>("cantidad") * 800) + (r.Field<int>("cantidad") * 200))
lblTotal.Text = suma.ToString();

Queries in LINQ to DataSet

It is clear that linq reduces the code

    
answered by 17.11.2018 в 05:17