21

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

Public Structure Product
    Public ItemNo As Int32
    Public Description As String
    Public Cost As Decimal
End Structure

...以及产品的通用列表:

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 值?换句话说,VB.NET 中返回值 120.90 的 LINQ 查询是什么,它反映了单个 LINQ 查询中所有三个产品成本值的总和?

4

2 回答 2

46

内置的 Sum 方法已经这样做了。

在 VB 中它看起来像这样:

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

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

ProductsList.Sum( (item) => item.Cost);
于 2009-11-23T19:31:06.063 回答
5

一种方法是:

Dim s = (From p As Product In products Select p.Cost).Sum()
于 2009-11-23T19:31:21.443 回答