-1

I can't check if my list length is 0. The code works if I remove the second part of the or; only check if the list is null.

@{
    @if( ViewBag.somelist != null || Enumerable.Count(ViewBag.somelist) == 0)
    {
        <p>list not null or empty</p>
    }
    @else
    {
        <p>list is empty</p>
    }
}

what I've tried:

  • Enumerable.Count(ViewBag.somelist) <1
  • ViewBag.somelist.Count() == 0
var somelist=Viewbag.somelist.Count;
@if( ViewBag.bbM9and10 != null || somelist == 0){}

also the interchangables to check if list is empty: >=0, <=0, <1, >=1

jgrewal
  • 342
  • 1
  • 10
  • https://stackoverflow.com/questions/28313324/how-to-check-if-viewbag-property-is-null-or-not-exists/28313648 – sagar1025 Jun 05 '21 at 01:42
  • thats only checking if the list null. my code already does that. I want to also check if the length of my list is equal to zero – jgrewal Jun 05 '21 at 01:46
  • Should that not check if the list != null or the list count is greater than 0, not equal to zero – Jay Mason Jun 05 '21 at 01:58
  • Alternatively it would be if(Not Null AND Count > 0) – Jay Mason Jun 05 '21 at 01:58
  • my viewbag is created somewhere along the line in my code. it isn't always present. That is the reason I'm checking if it is null. once it is created however. I want to check if the list is empty if enough indexes are removed to make the list length zero – jgrewal Jun 05 '21 at 02:04

2 Answers2

0

You should be able to just use Any() here, replacing your || for an && as mentioned in the comments, because you're checking if the list is not null and not empty:

@{
    @if(ViewBag.somelist != null && ViewBag.somelist.Any())
    {
        <p>list not null or empty</p>
    }
    @else
    {
        <p>list is empty</p>
    }
}

You can safely call it because the execution will never hit that point if somelist is null.

0

Problem with your code is || operator. For || operator when first statement is true or false, second statement will always gets executed. In your case, If ViewBag.somelist is null, second statement will also gets executed and it will then throw ArgumentNullException. To overcome this use && in place of ||. It will act as a short circuit and when first statement is true only then second will get executed else it execution will move to next line.

anand shukla
  • 666
  • 5
  • 14