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?
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#.
Items select new { Sum(p. Total), Sum(p. Done)};
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With