How to check all properties of an object whether null or empty?

后端 未结 9 1314
星月不相逢
星月不相逢 2020-11-28 06:41

I have an object lets call it ObjectA

and that object has 10 properties and those are all strings.

 var myObject = new {Property1=\"\",P         


        
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 07:06

    Here you go

    var instOfA = new ObjectA();
    bool isAnyPropEmpty = instOfA.GetType().GetProperties()
         .Where(p => p.GetValue(instOfA) is string) // selecting only string props
         .Any(p => string.IsNullOrWhiteSpace((p.GetValue(instOfA) as string)));
    

    and here's the class

    class ObjectA
    {
        public string A { get; set; }
        public string B { get; set; }
    }
    

提交回复
热议问题