Home > Software engineering >  How to derive any of the inner classes having count > 0 using linq or other approach
How to derive any of the inner classes having count > 0 using linq or other approach

Time:12-23

How to derive any of the inner list of classes having count > 0 using linq or other approach

ParentClass

ParentClass contains 10 inner classess - ChildClass1, ChildClass2, ChildClass3,...ChildClass10

class

public class ParentClass
{
    public List<ChildClass1> ChildClass1 { get; set; }
    public List<ChildClass2> ChildClass2 { get; set; }
    .
    .
    public List<ChildClass10> ChildClass10 { get; set; }
}

I having ParentClassObj from which how can I derive any of the inner class having count > 0.

I have one solution but it is not feasible to check for all 10 inner list of classes which is as below

if(!(ParentClassObj.ChildClass1.Any() && ParentClassObj.ChildClass2.Any() ...)
{
  // return not found
}

Is there any optimized solution using Linq or other approach to derive. Thanks

CodePudding user response:

The reflection way. Please see the IsAllChildCountsMoreThanZero method and change to what you want.

        public class ParentClass
        {
            public List<ChildClass1> ChildClass1 { get; set; }
            public List<ChildClass2> ChildClass2 { get; set; }
            public List<ChildClass10> ChildClass10 { get; set; }

            public bool IsAllChildCountsMoreThanZero()
            {
                foreach (var prop in typeof(ParentClass).GetProperties())
                {
                    var propType = prop.PropertyType;

                    if (propType.IsGenericType && (propType.GetGenericTypeDefinition() == typeof(List<>)))
                    {
                        var propertyValue = prop.GetValue(this, null);
                        if (propertyValue == null) return false;
                        var listPropertyValue = (IList)propertyValue;
                        if (listPropertyValue.Count == 0)
                        {
                            return false;
                        }
                    }
                }
                return true;
            }
        }
  • Related