Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through an object's properties and get the values for those of type DateTime

I have a list of objects (Cars). For each car in the list I need to loop through it and find any properties of type DateTime. If I find a property of DateTime I need to get the value and do a time conversion. For now lets just print out the DateTime property value to the console. I am having issues understanding what I need to put in the first parameter of the prop.GetValue function. Any help would be appreciated!

foreach (var car in carList) {       foreach (PropertyInfo car in car.GetType().GetProperties())     {         var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;         if (type == typeof (DateTime))         {              Console.WriteLine(prop.GetValue(???, null).ToString());         }     } } 
like image 568
Sealer_05 Avatar asked Apr 15 '16 20:04

Sealer_05


People also ask

Which loop is used to loop through an object properties?

for...in Loop The most straightforward way to loop through an object's properties is by using the for...in statement. This method works in all modern and old browsers including Internet Explorer 6 and higher.

Can you loop through properties of an object JavaScript?

Object. entries() is the recommended method for iterating over an object's properties in JavaScript. Since the method returns a multidimensional array, we can greatly simplify our code by using the array destructuring syntax to retrieve each property into a separate variable.


1 Answers

You need to use car as the first parameter:

foreach (var car in carList) {       foreach (PropertyInfo prop in car.GetType().GetProperties())     {          var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;          if (type == typeof (DateTime))          {               Console.WriteLine(prop.GetValue(car, null).ToString());          }     } } 
like image 139
aybe Avatar answered Oct 14 '22 04:10

aybe