我不知道如何在標題中解釋,所以我盡可能詳細地描述了我的擔憂:
我有一個具有不同屬性的物件串列,我通過一個名為“OriginID”的屬性和一個 LINQ 查詢對它們進行分組,以獲得不同屬性(NetTotal 和 ShippingCost)的總和。
由于我有多個屬性要獲得總和,因此我現在需要為每個組元素復制 LINQ 查詢(我有更多欄位,例如“OriginID”,例如 CountryID 等等。
Dim ListA = SalesTurnoverResult.GroupBy(
Function(x) x.OriginID).Select(
Function(a) New With {
Key .OriginID = a.Key,
Key .sum_a = a.Sum(Function(s) s.NetTotal),
Key .sum_b = a.Sum(Function(s) s.ShippingCost)})
我想將“一個”查詢封裝到一個函式中,其中組(即物件的屬性)可以作為引數給出,如下所示:
Public SubGetGroupedSummary(NameOfProperty As .... [the property])
Dim ListA = SalesTurnoverResult.GroupBy(
Function(x) x.[NameOfProperty]).Select(
Function(a) New With {
Key .OriginID = a.Key,
Key .sum_a = a.Sum(Function(s) s.NetTotal),
Key .sum_b = a.Sum(Function(s) s.ShippingCost)})
End Sub
甚至有可能這樣做嗎?
我添加了更多細節:
Public SalesTurnoverResult As List(Of SummaryClass)
'The (Sample)Class
Public Class SummaryClass
Public Property NetTotal As Single'Sum
Public Property ShippingCost As Single'Sum
Public Property InvoiceCountry As Integer'Group
Public Property OriginID As Single'Group
End Class
uj5u.com熱心網友回復:
一個簡單的解決方案是包含一個選擇案例:
ListA = SalesTurnoverResult.GroupBy(
Function(x)
Select Case NameOfProperty
Case "OriginID" : Return x.OriginID
Case "InvoiceCountry" : Return x.InvoiceCountry
End Select
End Function
).Select(
Function(a) New With {
Key .OriginID = a.Key,
Key .sum_a = a.Sum(Function(s) s.NetTotal),
Key .sum_b = a.Sum(Function(s) s.ShippingCost)})
編輯#1:
這是我嘗試過的:
....
With SalesTurnoverResult
Dim sc As New SummaryClass
sc.NetTotal = 100 : sc.ShippingCost = 20 : sc.InvoiceCountry = 1 : sc.OriginID = 1000 : sc.Str = "abc"
.Add(sc)
sc = New SummaryClass
sc.NetTotal = 50 : sc.ShippingCost = 25 : sc.InvoiceCountry = 1 : sc.OriginID = 1001 : sc.Str = "efg"
.Add(sc)
sc = New SummaryClass
sc.NetTotal = 120 : sc.ShippingCost = 25 : sc.InvoiceCountry = 2 : sc.OriginID = 1002 : sc.Str = "jkl"
.Add(sc)
sc = New SummaryClass
sc.NetTotal = 50 : sc.ShippingCost = 20 : sc.InvoiceCountry = 3 : sc.OriginID = 1001 : sc.Str = "abc"
.Add(sc)
End With
GetGroupedSummaryStrictON("OriginID")
GetGroupedSummaryStrictON("InvoiceCountry")
GetGroupedSummaryStrictON("Str")
....
....
Public Sub GetGroupedSummaryStrictON(NameOfProperty As String)
Try
Dim ListA = SalesTurnoverResult.GroupBy(
Function(x) As Object
Select Case NameOfProperty
Case "OriginID" : Return CSng(x.OriginID)
Case "InvoiceCountry" : Return CInt(x.InvoiceCountry)
Case Else ' x.Str
End Select
Return CType(x.Str, String)
End Function).Select(
Function(a) New With {
Key .OriginID = a.Key,
Key .sum_a = a.Sum(Function(s) s.NetTotal),
Key .sum_b = a.Sum(Function(s) s.ShippingCost)}).ToArray
Console.WriteLine(NameOfProperty)
For Each a In ListA
Console.WriteLine(String.Format("{0} {1} {2}", a.OriginID, a.sum_a, a.sum_b))
Next
Console.WriteLine("--------------------")
Catch ex As Exception
End Try
End Sub
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/446631.html
