5

I get the properties of some object

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

How can I get names of the properties, which values are not null?

And how can I get those?

1
  • add x.GetValue(<yourObject>, null) != null as a where clause.
    – Sin
    Aug 5, 2017 at 9:35

1 Answer 1

10

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 a Tuple for older C# version:

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();
}
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.