首页 > 解决方案 > 处理新 linq 对象中的空返回 c#

问题描述

我要去做什么?我需要将一个新创建的对象发布到数据库,传入的对象可能有一个空值。创建的对象设置#nullible true在需要的地方。

当数据进入并且我落在我的对象中的一个空字符串上时,我得到一个空引用并抓住了。

我的代码:

Objects.Data.Info.StoredData postData = new Objects.Data.Info.StoredData
                                {
                                    Name = data.data.Name,
                                    Type = data.data.Type,
                                    Price = data.data.Price,
                                    Indicator = data.data.Indicator,
                                    Scan = data.data.Scan,
                                    Comment = data.data.Extra
                                };
                                db.Information.Add(postData);
                                db.SaveChanges();

data.data.Extra 有时可以为空。

我通常会写 if 语句来解决这个问题,但不觉得这是最好的做法。我应该往哪个方向走?我检查了其他一些问题和 msdn,但找不到明确的路径。

谢谢。

标签: c#linq.net-core

解决方案


当属性为 null 时,您可以使用运算符简洁地默认为空字符串??,如下所示:

Comment = data.data.Extra ?? ""  
//the value on the right is used if the expression on the left is null

??被称为“null-coalescing”运算符:https ://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator


如果您还想处理为 null 的中间属性(我认为这不适用于这种情况,但很高兴知道),并且仍想默认为空字符串,您可以将其与 Eugene 的使用?.like so的建议结合起来:

Comment = data?.data?.Extra ?? ""

?.被称为“空条件”运算符:https ://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-


推荐阅读