获取非null的属性的名称

4 .net c# linq reflection

我得到了一些对象的属性

var properties = typeof(T).GetProperties()
                          .Select(x => x.Name)
                          .ToList()
Run Code Online (Sandbox Code Playgroud)

如何获取属性的名称,哪些值不是null

我怎么能得到那些?

Ale*_*eev 8

试试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();
}
Run Code Online (Sandbox Code Playgroud)

或者您可以Tuple为旧的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();
}
Run Code Online (Sandbox Code Playgroud)