简体   繁体   中英

Checking content of not null values in IEnumerable

I have a foreach loop that prints out the values of every row in SQL table if Status column has 'Pending' value.

@foreach (var item in Model)
{
    if (item.Status == "Pending") {
        // code for review
    }
    else {
        <p>nothing to review</p>
    }
}

In this sample 'nothing to review' is shown every time Status has a value other than "Pending".

Checking for not null before foreach loop returns true with the code below:

var test = Model.Any(model => model.Status != null);
<p>@test</p> // returns True since there are several not null values

But it throws an error when

if (Model.Any(model => model.Status.Contains("Pending"))) {
<p>Status has pending</p>

since there are NULL value and it cannot be checked for .Contains

How can I check the 'Pending' value before the foreach loop? So when there are records with Pending value they will show (I already have the code for this). But if there are no records where Status == "Pending" it will show "nothing to review" only once.

Update. Here is what I used.

if (Model.Any(model => Convert.ToBoolean(model.Status?.Contains("Pending")))){
    <p>(Status has pending) Please review the following</p>

    @foreach (var item in Model)
    {
        // code for review
    }
}
else{
    <p>There are no documents to review</p>
}
if(model?.Status?.Contains("Pending"))

或者

if(model != null && model.Status != null && model.Status.Contains("Pending"))

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