tags:

views:

734

answers:

2

Greetings:

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?

Thank you in advance for your time and help...

+3  A: 

the built in Sum method does this already.

in C# (sorry for not knowing linq in VB) it would look like this

ProductsList.Sum( (item) => item.Cost);
McKay
VB's approach: ProductList.Sum(Function(x) x.Cost)
Nathan
Many thanks to both McKay, Nathan, and eidylon for your time and help. All of the answers were spot on and worked for me. Your answers were far more easy to read, understand and implement than trying to use disassembled code that I originally implemented evaluated in C#. {:-P If you'd like I can post the disassembly from .NET Reflector. Although both approaches are logically and semantically the same, the syntax for the code emitted by both is slightly different and makes for interesting reading.Again, many thanks...
ClockEndGooner
A: 

One way would be:

Dim s = (From p As Product In products Select p.Cost).Sum()
eidylon