你怎样检查一个列表中没有空值?

huangapple go评论69阅读模式
英文:

How can i check there are no nulls in a list?

问题

Sure, here's the translated code part:

我有一个列表,如何检查其中是否有空值?

所以我有一个客户端ID列表

我进行以下操作

var listA = (clientIds == null || !clientIds.Any(t => t.User?.Email == userBody.Email))

但我想先检查t.User不为空。Userclientids中的一个对象

我该怎么做?

英文:

I have a list , how can i check that for nulls ?

so i have a list clientIds

I do the following

var listA = (clientIds== null || !clientIds.Any(t => t.User.Email == userBody.Email))

but i want to check first that t.User is not null. User is an object in clientids

how can i do this ?

答案1

得分: 1

修复在C#代码中t.User为null时发生的错误,您可以修改条件以在访问Email属性之前包括一个null检查。以下是您代码的更新版本:

var listA = (clientIds == null || !clientIds.Any(t => t.User != null && t.User.Email == userBody.Email));

在修改后的代码中,添加了t.User != null作为在访问Email属性之前的额外检查。这确保了如果t.User为null,条件将评估为false,并防止null引用错误。

您还可以使用null条件运算符(?.)仅在t.User不为null时有条件地访问Email属性。如果t.User为null,整个表达式t.User?.Email将评估为null,然后将与userBody.Email进行比较。

var listA = clientIds == null || !clientIds.Any(t => t.User?.Email == userBody.Email);
英文:

To fix the error that occurs when t.User is null in your C# code, you can modify the condition to include a null check before accessing the Email property. Here's an updated version of your code:

var listA = (clientIds == null || !clientIds.Any(t => t.User != null && t.User.Email == userBody.Email));

In the modified code, t.User != null is added as an additional check before accessing the Email property. This ensures that if t.User is null, the condition will evaluate to false and prevent the null reference error.

You can also use the null condition operator (?.) to conditionally access the Email property only if t.User is not null. If t.User is null, the entire expression t.User?.Email will evaluate to null, which will then be compared with userBody.Email.

var listA = clientIds == null || !clientIds.Any(t => t.User?.Email == userBody.Email);

huangapple
  • 本文由 发表于 2023年5月25日 08:43:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定