简体   繁体   English

检查 IEnumerable 中非空值的内容

[英]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.如果Status列具有'Pending'值,我有一个 foreach 循环会打印出 SQL 表中每一行'Pending'值。

@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".在此示例中,每次 Status 具有除“Pending”以外的值时都会显示“nothing to review”。

Checking for not null before foreach loop returns true with the code below:使用以下代码在 foreach 循环返回 true 之前检查 not null:

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因为有 NULL 值并且无法检查 .Contains

How can I check the 'Pending' value before the foreach loop?如何在 foreach 循环之前检查“Pending”值? 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.但是如果没有 Status == "Pending" 的记录,它只会显示一次 "nothing to review"。

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"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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