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

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

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

1
2
3
4
5
Public Structure Product
    Public ItemNo As Int32
    Public Description As String
    Public Cost As Decimal
End Structure

...以及产品的一般清单:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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)

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


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

在VB中,它看起来像这样:

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

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

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


一种方法是:

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