Convert Data Table to INT and Add Values

3

Good morning,

I need help in the following, I have a table that is filled by a DataTable, now I include my project a dropdownlist (DDL) to change a column in specifies depending on the date selected in the DDL, My inconvenience is with the part to replace the values of the column with the new one taking into account that the result can be more than one record so I would like to make a sum and the result to place it in an INT and make the replacement in the column, I have the following code:

      if (ddlMontoPorMes.SelectedIndex > 0)
            {

                foreach (DataRow row in dt.Rows)
                {

                    foreach (DataColumn MONTOREC in dt.Columns)
                    {
                        foreach (DataRow dtRow in dt.Rows)
                        {
                            object fielsd = dtRow["NROACCRUAL"];
                            //Hago la busqueda de los nuevos valores por aqui 
                            DataTable dt1 = Helper_wsWillisBudget.SumaRecibosPorMes(fielsd.ToString(), ddlMontoPorMes.SelectedValue);
                            //Aqui quiero sumar todos los valores para tener un solo resultado y asignarlo a la columna
                            int suma = int.Parse(dt1);
                            row.SetField("MONTOREC", dt1);
                        }


                    }
                }

            }

Thank you very much in advance

    
asked by Hans 27.03.2017 в 19:32
source

1 answer

2

To add the rows of a DataTable you would use LINQ, using the extension AsEnumerable for DataTable and Field for DataRow .

if (ddlMontoPorMes.SelectedIndex > 0)
{
    foreach (DataRow row in dt.Rows)
    {
        foreach (DataRow dtRow in dt.Rows)
        {           
            DataTable dt1 = Helper_wsWillisBudget.SumaRecibosPorMes(dtRow["NROACCRUAL"].ToString(), ddlMontoPorMes.SelectedValue);
            int suma = dt1.AsEnumerable().Sum(x => x.Field<int>(0));
            row["MONTOREC"] = suma;
        }
    }
}

As I indicated in the comment, the answer only considers the first column when using x.Field<int>(0) . If you have a defined column, it would be x.Field<int>("MiColumna") .

Another option that you could use to add a column is DataTable.Compute .

decimal monto = 0.0M;
DataTable dt = new DataTable();
dt.Columns.Add("Monto", typeof(int));

dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(3);                        

monto = Convert.ToDecimal(dt.Compute("Sum(Monto)", ""));

Console.WriteLine(monto);

Example

    
answered by 27.03.2017 в 21:11