Get property names that are not null

I am getting properties of some object

var properties = typeof(T).GetProperties()
                          .Select(x => x.Name)
                          .ToList()

      

How can I get the names of properties whose values ​​are not null

?

And how can I get them?

+3


source to share


1 answer


Try this code for C # 7:

public static void GetProps<T>(T obj)
{
    var result = typeof(T).GetProperties()
        .Select(x => new { property = x.Name, value = x.GetValue(obj) })
        .Where(x => x.value != null)
        .ToList();
}

      



Or you can create Tuple

for an older version of C #:

public static void GetProps<T>(T obj)
{
    var result = typeof(T).GetProperties()                  
        .Select(x => Tuple.Create(x.Name, x.GetValue(obj)))
        .Where(x => x.Item2 != null)
        .ToList();
}

      

+4


source







All Articles