VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,741 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hallo,
I have code something like this,
Dim C1= CType(Form1.BS_Classes.Current, Class1)
Dim value As Integer = C1.Class2.Sum(Function(x) x.Property1)
I have many classes or custom objects inside Class1. How do i pass them in a loop so that it goes like C1.Class2.sum and c1.Class3.sum like this?. Is there a way to also get custom objects automatically from Class1 and then loop?.
Thanks
Hi,
try following console demo:
Imports System.Reflection
Module Module61
Sub Main()
Try
Call (New Demo).Execute()
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
Console.WriteLine("Continue enter key")
Console.ReadKey()
End Sub
Friend Class Demo
Friend Sub Execute()
' get refernce '
Dim C1 = New Class1
' sum all property values '
Dim value1 As Integer = C1.Class2.Sum(Function(x) x.Property1)
Dim value2 As Integer = C1.Class3.Sum(Function(x) x.Property1)
Console.WriteLine(value1 + value2)
' sum with reflection '
Dim value3 As Integer
Dim pi() As PropertyInfo = C1.GetType().GetProperties(BindingFlags.Instance Or BindingFlags.Public)
For i = 0 To pi.GetUpperBound(0)
Dim li = TryCast(pi(i).GetValue(C1), IEnumerable(Of I1))
If li IsNot Nothing Then value3 += li.Sum(Function(x) x.Property1)
Next
Console.WriteLine(value3)
End Sub
End Class
Friend Class Class1
Public Sub New()
For i = 1 To 3
Class2.Add(New C2 With {.Property1 = i})
Next
For i = 4 To 6
Class3.Add(New C3 With {.Property1 = i})
Next
End Sub
Public Property Class2 As New List(Of C2)
Public Property Class3 As New List(Of C3)
Public Property OtherProperty As Object
End Class
Friend Class C2
Implements I1
Friend Property Property1 As Integer Implements I1.Property1
End Class
Friend Class C3
Implements I1
Friend Property Property1 As Integer Implements I1.Property1
End Class
Friend Interface I1
Property Property1 As Integer
End Interface
End Module
Thank you very much Peter.