English 中文(简体)
VB.NET LINQ Query: Getting The Sum of All Values For A Specific Structure Member
原标题:

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?

最佳回答

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);
问题回答

One way would be:

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




相关问题
Is Shared ReadOnly lazyloaded?

I was wondering when I write Shared ReadOnly Variable As DataType = New DataType() Or alternatively Shared ReadOnly Variable As New DataType() Is it lazy loaded or as the instance initializes? ...

Entertaining a baby with VB.NET

I would like to write a little application in VB.NET that will detect a baby s cry. How would I get started with such an application?

Choose Enter Rather than Pressing Ok button

I have many fields in the page and the last field is a dropdown with list of values. When I select an item in a dropdown and press Enter, it doesn t do the "Ok". Instead I have to manually click on Ok ...

ALT Key Shortcuts Hidden

I am using VS2008 and creating forms. By default, the underscore of the character in a textbox when using an ampersand is not shown when I run the application. ex. "&Goto Here" is not ...

Set Select command in code

On button Click I want to Set the Select command of a Gridview. I do this and then databind the grid but it doesn t work. What am i doing wrong? protected void bttnView_Click(object sender, ...

Hover tooltip on specific words in rich text box?

I m trying to create something like a tooltip suddenly hoovering over the mouse pointer when specific words in the richt text box is hovered over. How can this be done?

热门标签