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

后端 未结 9 1331
星月不相逢
星月不相逢 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:15

    You can do it using Reflection

    bool IsAnyNullOrEmpty(object myObject)
    {
        foreach(PropertyInfo pi in myObject.GetType().GetProperties())
        {
            if(pi.PropertyType == typeof(string))
            {
                string value = (string)pi.GetValue(myObject);
                if(string.IsNullOrEmpty(value))
                {
                    return true;
                }
            }
        }
        return false;
    }
    

    Matthew Watson suggested an alternative using LINQ:

    return myObject.GetType().GetProperties()
        .Where(pi => pi.PropertyType == typeof(string))
        .Select(pi => (string)pi.GetValue(myObject))
        .Any(value => string.IsNullOrEmpty(value));
    

提交回复
热议问题