VB.NET LINQ 查询:获取特定结构成员的所有值的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1785403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:32:01  来源:igfitidea点击:

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

vb.netlinqsum

提问by ClockEndGooner

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

在 VB.NET 中,假设我有以下结构:

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?

我将如何定义 LINQ 查询以对列表中的所有 Product.Cost 值求和?换句话说,VB.NET 中的 LINQ 查询返回值 120.90 是什么,它反映了单个 LINQ 查询中所有三个产品成本值的总和?

回答by McKay

The built in Sum method does this already.

内置的 Sum 方法已经做到了这一点。

In VB it looks like this:

在VB中它看起来像这样:

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

In C# it looks like this:

在 C# 中,它看起来像这样:

ProductsList.Sum( (item) => item.Cost);

回答by eidylon

One way would be:

一种方法是:

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