Add values of a column of a datatable using linq

1

With the following table:

| Animales | cantidad |
-----------------------
| Perros   | 5        |
| Gatos    | 3        |
| Loros    | 2        |

I create the datatable:

   Dim tabla As New DataTable()
        tabla.Columns.AddRange(New DataColumn(1) {New DataColumn("Animales", GetType(String)),
                                               New DataColumn("cantidad", GetType(Integer))})
        tabla.Rows.Add("Perros", 5)
        tabla.Rows.Add("Gatos", 3)
        tabla.Rows.Add("Loros", 2)

I want to get the sum of the total animals: 10

Using MySQL, it would be something like that

SELECT SUM(cantidad) FROM tabla

My attempts in linq go around this formula but without success:

Dim qry = From a in tabla
          Let Animal = a(0)
          Let Cantidad = a(1)
          Select sum(cantidad)

I still feel very clumsy with linq so I would appreciate any help. Greetings

    
asked by Otxoto 01.04.2017 в 20:11
source

1 answer

1

A few options depending on the syntax you prefer:

Dim total = (From a In tabla.AsEnumerable()
             Select a.Field(Of Integer)("cantidad")).Sum()

Demo

o ...

Dim total = tabla.AsEnumerable().Sum(Function(t) t.Field(Of Integer)("cantidad"))

Demo

You can find more information about the peculiarities of using LINQ with DataTable here: LINQ query on a DataTable .

    
answered by 01.04.2017 / 21:03
source