vendredi 14 septembre 2018

Null validation for getting property values using reflection

Here i am trying to add a generic list of values to a dictionary.

Below is the DocDetails class

public class DocDetails
{
   public string DocId { get; set; }
   public string Description { get; set; }
   public string Category { get; set; }
}

Iam getting a list of DocDetails in docDetailsList object. Using this am getting each item of DocDetails and getting the property name and value and then adding to a Dictionary.

Dictionary<string, List<object>> docDict = new Dictionary<string, List<object>>();

  foreach (var doc in docDetailsList)
     {
          var dict = doc.GetType().GetProperties().ToDictionary(
            m => m.Name, m => new List<object>()
             {
                m.GetValue(doc, null).ToString()
             });
         docDict.Add(dict);
      }

When trying to get property value in this line m.GetValue(doc, null).ToString() getting exception if the value is null. How can i validate that , even if its null i need to add that property name to the list with an empty value. Can any one help me out here please





Aucun commentaire:

Enregistrer un commentaire