我有一个List<Object>
,其中Object包含Name,Month,Type,Value。
是否可以根据类型对所有值求和,然后根据月份?
我在VB.NET中使用.NET 3.0 我正在做4 For循环,但它需要一段时间才能运行。 有更快的方法吗?
为了澄清,我有这样的事情:
Name | Month | Type | Value
-----------------------------
hello | Jan | A | 1
hello | Jan | A | 2
hello | Jan | B | 2
hello | Feb | A | 3
hello1 | Jan | A | 6
hello1 | Jan | A | 2
hello1 | Jan | B | 2
hello1 | Feb | A | 3
我想把它制作成这个
Name | Month | Type | Value
---------------------------
hello | Jan | A | 3
hello | Jan | B | 2
hello | Feb | A | 3
hello1 | Jan | A | 8
hello1 | Jan | B | 2
hello1 | Feb | A | 3
答案 0 :(得分:1)
如果无法使用LINQ:
您可以使用Dictionarys来保存月份值和类型值。所以你只需要一个循环来填充所有。这是一个例子:
Foo是你的对象,FooType是你的类型:
Class Foo
Public Enum FooType As Int32
FirstType = 1
SecondType = 2
ThirdType = 3
FourthType = 4
FifthType = 5
End Enum
Public Property Name As String
Public Property Month As Date
Public Property type As FooType
Public Property value As Double
End Class
加载一些样本数据:
Dim monthRnd As New Random(Date.Now.Millisecond)
Dim yearRnd As New Random(Date.Now.Millisecond)
Dim valueRnd As New Random(Date.Now.Millisecond)
Dim fooTypeRnd As New Random(Date.Now.Millisecond)
Dim allFoos As New List(Of Foo)
For i As Int32 = 1 To 1000
Dim foo As New Foo
foo.Name = i & ". Foo"
foo.type = CType(fooTypeRnd.Next(1, 5), Foo.FooType)
foo.Month = New Date(2000 + yearRnd.Next(0, 12), monthRnd.Next(1, 12), 1)
foo.value = valueRnd.Next(1, 10000) * valueRnd.NextDouble()
allFoos.Add(foo)
Next
按类型和按月分组填写总值:
Dim sumTotal As Double = 0D
Dim monthSums As New Dictionary(Of Date, Double)
Dim typeSums As New Dictionary(Of Foo.FooType, Double)
For Each f As Foo In allFoos
sumTotal += f.value
If typeSums.ContainsKey(f.type) Then
typeSums(f.type) += f.value
Else
typeSums.Add(f.type, f.value)
End If
If monthSums.ContainsKey(f.Month) Then
monthSums(f.Month) += f.value
Else
monthSums.Add(f.Month, f.value)
End If
Next
现在您可以通过Dictionary键轻松访问这些值。 例如:
Dim feb2010Value As Double = 0d
Dim feb2010 As New Date(2010, 2, 1)
If monthSums.ContainsKey(feb2010) Then
feb2010Value = monthSums(feb2010)
End If
答案 1 :(得分:0)
我仍然不确定你想要什么,但是你的例子让你看起来好像按名称和按月分类和按类型分组。< / p>
无论哪种方式,这都是集团的聚合。以下应该有效。
Dim result = From obj In objects _
Group obj By obj.Name, obj.Month, obj.Type Into _
Value = Sum(obj.Value) _
Select Name, Month, Type, Value
但是,您不应该使用List(Of Object)
- 而是使用正确的对象类型。
(未经测试,没有VB方便,因此实际语法可能会有很小的偏差。)