Reputation: 6733
How do I iterate through all the value types of an object and convert that into a Dictionary? I was heading the reflection way
obj.GetType().GetProperties()
but that gives both value types and references types.
Upvotes: 1
Views: 101
Reputation: 65117
You can just use the IsValueType
property of the PropertyInfo
Type
:
obj.GetType().GetProperties().Where(x => x.PropertyType.IsValueType)
Adding it to a dictionary becomes:
foreach (var propertyInfo in obj.GetType().GetProperties().Where(x => x.PropertyType.IsValueType)) {
dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(obj));
}
Where the key is the name and the value is the value in the obj
instance.
Upvotes: 2