Iterating through dynamic properties from IList

I am trying to create an attribute validator that, given a list, should ensure that there is at least one element in the list.

So I have this for the moment

public override bool IsValid(object value)
{
    var list = value as IList;

    if (list != null)
        return list.Count >= 1;

    return false;
}

      

My problem is that I can get a list with more than one element, but the properties of all those elements are zero, so I need to iterate over each property to check them. And I'm not really sure how I can achieve this without knowing the property name.

+3


source to share


2 answers


As per your comment, you have your own type. First, use it in your method declaration and don't use an object. Type of throw, as well as boxing and unboxing of the road:

public override bool IsValid(IEnumerable<MyType> myObjects)

      

Second, enhance your own type with a property IsEmpty

:



public class MyType
{
    public bool IsEmpty
    {
        get
        {
            // define here when your type is empty
        }
    }

    ...
}

      

Then your final check is simple:

public override bool IsValid(IEnumerable<MyType> myObjects)
{
    return myObjects != null ? myObjects.Any() : false;
}

      

+1


source


I would recommend working with IEnumerable, simply because it works with collections other than lists.

But besides that. You can use the counter that is present on each enumeration. Once you find the first non-null elements, return true:

public override bool IsValid(object value)
{
    var list = value as IEnumerable;
    var enumerator = list != null ? list.GetEnumerator() : null;

    if (enumerator != null)
        while(enumerator.MoveNext())
            if(enumerator.Current != null)
                return true;

    return false;
}

      



You could have done better the second time around. By calling Cast<object>()

to your list, you get a general IEnumerable<object>

one on which you can use all mighty linqs and just call Count(e => e != null)

in your enum:

public override bool IsValid(object value)
{
    var list = value as IEnumerable;
    var enumerable = list != null ? list.Cast<object>() : null;
    return enumerable != null && enumerable.Count(e => e != null) >= 1;
}

      

-1


source







All Articles