Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET LINQ Query: Getting The Sum of All Values For A Specific Structure Member

Tags:

In VB.NET, let's assume I have the following Structure:

Public Structure Product
    Public ItemNo As Int32
    Public Description As String
    Public Cost As Decimal
End Structure

... and a Generic List of the Products:

Dim ProductsList As New List(Of Product)

Dim product1 As New Product

With product1
    .ItemNo = 100
    .Description = "Standard Widget"
    .Cost = 10D
End With

ProductsList.Add(product1)

Dim product2 As New Product

With product2
    .ItemNo = 101
    .Description = "Standard Cog"
    .Cost = 10.95D
End With

ProductsList.Add(product2)

Dim product3 As New Product

With product3
    .ItemNo = 101
    .Description = "Industrial Strenght Sprocket"
    .Cost = 99.95D
End With

ProductsList.Add(product3)

How would I define a LINQ Query to Sum all of the Product.Cost values in the List? In other words, what would be the LINQ Query in VB.NET to return the value 120.90, which reflects the sum of all three Product Cost values in a single LINQ Query?

like image 471
ClockEndGooner Avatar asked Nov 23 '09 19:11

ClockEndGooner


People also ask

How do you find the sum of Linq?

In LINQ, you can find the sum of the given numeric elements by using the Sum() method. This method calculates the sum of the numeric value present in the given sequence. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.

How do I sum two columns in Linq?

Items select new { Sum(p. Total), Sum(p. Done)};


1 Answers

The built in Sum method does this already.

In VB it looks like this:

ProductList.Sum(Function(item) item.Cost)

In C# it looks like this:

ProductsList.Sum( (item) => item.Cost);
like image 179
McKay Avatar answered Sep 17 '22 16:09

McKay