简体   繁体   English

Null 检查是否在 C#

[英]Null checking for if then in C#

I am checking two conditions which is following in C#:我正在检查 C# 中的两个条件:

 if (result.Data.Count > 0)
 {
     if(result.Data[0].AdditionalData != null)
      {
         // To Do
      }
  } 

My confusion is there is any better way to check these in a single if condition?我的困惑是有没有更好的方法在一个 if 条件下检查这些?

I am trying to use Null-Condition operator, but did not work it.我正在尝试使用 Null-Condition 运算符,但没有成功。 Null-Conditional operator in MSDN MSDN 中的空条件运算符

You can create extension method on IEnumerable and use it您可以在 IEnumerable 上创建扩展方法并使用它

    public static bool HasValue<T>(this IEnumerable<T> source, int index)
    {
        if (source == null)
            return false;

        return source.Count() > index && source.ElementAt(index) != null;
    }

// usage
if(result.Data.HasValue(0))
{
}

One liner using System.Linq .一个使用System.Linq的衬垫。

if (result.Data.FirstOrDefault()?.AdditionalDate != null)
{
 
} 

You forgot to check the value is empty or not.您忘记检查该值是否为空。 Empty or null is differences value.空或 null 是差异值。

Like written also by @Hans Killian try to use the extensions already there for IEnumerables In your case I think .ElementAtOrDefault(0) (or if you always want to use index 0 just use .FirstOrDefault() ) is the best fit for you here.就像@Hans Killian也写的一样,尝试使用IEnumerables已经存在的扩展在你的情况下,我认为.ElementAtOrDefault(0) (或者如果你总是想使用索引0,只需使用.FirstOrDefault() )在这里最适合你.

if (result?.Data != null && result.Data.Any())
{
    /// Expecting 'AdditionalData' is `string`
    if (!string.IsNullOrEmpty(result.Data.ElementAtOrDefault(0)?.AdditionalData))
    {
        Console.WriteLine("Null check working...");
    }
    else
    {
        Console.WriteLine("AdditionalData is null or empty!");
    }
}
else
{
    Console.WriteLine("No data!");
}

Full working example can be found here完整的工作示例可以在这里找到

I think the best way to have clean and good code is to use FluentValidation.我认为拥有干净和良好代码的最佳方法是使用 FluentValidation。 Please note the following code snippet:请注意以下代码片段:

  public class RegisterValidator : AbstractValidator<RegisterDTO>
{
    public RegisterValidator()
    {
        RuleFor(a => a.PhoneNumber).NotNull().WithMessage(Utility.GetEnumTitlePersian(enmErrorMessage.InValidMobileNumber));
        RuleFor(a => a.PhoneNumber).NotEmpty().WithMessage(Utility.GetEnumTitlePersian(enmErrorMessage.InValidMobileNumber));
        RuleFor(a => a.PhoneNumber).MinimumLength(11).WithMessage(Utility.GetEnumTitlePersian(enmErrorMessage.InValidMobileNumber));
        RuleFor(a => a.PhoneNumber).MaximumLength(11).WithMessage(Utility.GetEnumTitlePersian(enmErrorMessage.InValidMobileNumber));
    }

} }

The above code is an example of validating a model to check null, empty and etc. and this code must check validation in business logic:上述代码是验证 model 以检查 null、空等的示例,此代码必须在业务逻辑中检查验证:

var validator = new RegisterValidator();
var validatorResult = await validator.ValidateAsync(register);

if (!validatorResult.IsValid)
    return BadRequest("", validatorResult.Errors[0].ToString());

It is very simple to use and very clean.它使用起来非常简单而且非常干净。 You can even perform multiple checks and get results through the error list This link is the site address of FluentValidation你甚至可以通过错误列表进行多次检查并得到结果 这个链接是FluentValidation的站点地址

Null conditional can work along with Any , and short-circuiting the next check Null 有条件可以和Any一起工作,短路下检查

if (result?.Data?.Any() && result.Data[0]?.AdditionalData != null)
{
    // to do
}

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

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