Last active
May 5, 2017 08:15
-
-
Save wolf99/310b1ce7eec5e8a64c1de69872980c0b to your computer and use it in GitHub Desktop.
VB.NET function to get a Dictionary of the names and values of the properties of a given object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Option Strict On | |
Option Explicit On | |
Imports System.Reflection | |
Module Gists | |
Public Function GetDictionaryOfProperties(ByRef o As Object) As Dictionary(Of String, Object) | |
Dim Properties As Dictionary(Of String, Object) = New Dictionary(Of String, Object) | |
#If Not USE_LOOP | |
Properties = (From x In o.GetType().GetProperties() | |
Select x).ToDictionary(Of String, Object) _ | |
(Function(x As PropertyInfo) (x.Name), ' Get string key from property name | |
Function(x As PropertyInfo) (x.GetGetMethod().Invoke(o, Nothing))) ' Get object value | |
#Else | |
' Equivalent loop version of the same thing | |
Dim PropertyInfos As PropertyInfo() = o.GetType().GetProperties() ' Get array of property infos | |
For Each x As PropertyInfo In PropertyInfos ' Step through each of the property infos | |
Dim PropertyName As String = x.Name ' Get string key from property name | |
Dim PropertyValue As Object = x.GetGetMethod().Invoke(o, Nothing) ' Get object value | |
Properties.Add(PropertyName, PropertyValue) | |
Next | |
#End If | |
Return Properties | |
End Function | |
End Module |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment