Search code examples
c#asp.net-mvc-3countienumerablehttppostedfilebase

count non-null elements of IEnumerable<HttpPostedFileBase>


I have a view model in asp .net mvc 3 which has

IEnumerable<HttpPostedFileBase> files

In the view, I have a for loop that creates 9 input tags for these files.

I want to implement a check on the server-side to ensure atleast 3 files are being uploaded.

I tried putting a condition

if(files.Count() > 2) { // code here } 

However, that returns 9 as it also counts the null elements.

I can think of implementing a counter myself as below:

int count = 0;
@foreach(var file in files) {
  if(file != null && file.ContentLength > 0) { 
    count++; 
  }
}

Is this the best way to do this or is there a functionality already in asp .net mvc for this.


Solution

  • files.Count(file=>file != null && file.ContentLength > 0);