How do I validate list has greater than zero non n

2019-06-25 04:56发布

问题:

I am trying to implmenet a file uploader that can take various amounts of files. The files input elemnts are all named the same so produce a list of files that MVC3 happily binds to.

So in my controller I have have

public virtual ViewResult UploadReceive(IEnumerable<HttpPostedFileBase> Files ){

This gets all the files it should. However all empty form file input elements are adding a null. This is stopping my basic non empty List validation in the controller from working as I want.

The validation is below:

public class EnsureMinimumElementsAttribute : ValidationAttribute
{
    private readonly int _minElements;
    public EnsureMinimumElementsAttribute(int minElements)
    {
        _minElements = minElements;
    }

    public override bool IsValid(object value)
    {
        var list = value as IList;
        if (list != null)
        {
            return list.Count >= _minElements;
        }
        return false;
    }
}

Any idea how I change the validation to generically count only non null elements?

回答1:

If you only want to count non-null objects you can use LINQ with an IList by using:

list.Cast<object>().Count(o => o != null)

Alternatively you can just loop and count each non-null object.

int count = 0;
foreach (var item in list)
{
    if (item != null)
        count++;
}