简体   繁体   中英

checking if a viewbag list is null or empty

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM