VB.NET LINQ Query: Getting The Sum of All Values F

2019-04-03 17:53发布

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?

标签: vb.net linq sum
2条回答
Rolldiameter
2楼-- · 2019-04-03 18:03

One way would be:

Dim s = (From p As Product In products Select p.Cost).Sum()
查看更多
女痞
3楼-- · 2019-04-03 18:13

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);
查看更多
登录 后发表回答