Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 895
Tripping Avatar asked Dec 09 '25 13:12

Tripping


2 Answers

files.Count(file=>file != null && file.ContentLength > 0);
like image 135
L.B Avatar answered Dec 12 '25 03:12

L.B


Use a predicate to filter the count:

files.Where(file => file != null).Count()

Or simpler, just files.Count(file => file != null).

like image 40
McGarnagle Avatar answered Dec 12 '25 01:12

McGarnagle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!