简体   繁体   English

如何解决 C# 中 linq 的 lambda 表达式中的对象引用错误?

[英]How to resolve object reference error in lambda expression of linq in c#?

I am working on WPF application.我正在研究 WPF 应用程序。 In which I am trying to fetch records from list as per required condition.在其中我试图根据需要的条件从列表中获取记录。 But when there is no any record found then it's giving me object reference not found error.但是当没有找到任何记录时,它会给我对象引用未找到错误。

var recordList = _outputVariables.ToList().Where(X => X.symbolName == _symbolName).ToList();
if (recordList != null)
{
       //more coding...
}

so as shown in code when _outputVariables have no any record match as per _symbolName then it's giving error of Object reference not set to an instance of an object.'所以如代码所示,当 _outputVariables 根据 _symbolName 没有任何记录匹配时,它会给出Object reference not set to an instance of an object.'错误Object reference not set to an instance of an object.' and X was null. X was null. . . So how can I handle this issue ?那么我该如何处理这个问题呢? please help for it.请帮忙。

Use the null-conditional operator that was introduced in C#6 (and don't call ToList() more than once):使用 C#6 中引入的空条件运算符(并且不要多次调用ToList() ):

var recordList = _outputVariables?.Where(X => X?.symbolName == _symbolName).ToList();
if (recordList != null)
{
    //more coding...
}

You can use like below as well你也可以像下面一样使用

 if (_outputVariables != null && _outputVariables.Count > 0)
            {
               var recordList = _outputVariables.Where(X => X != null && !string.IsNullOrEmpty(X.symbolName) && X.symbolName == _symbolName);

            }

var recordList = _outputVariables.ToList().Where(X => X.symbolName == _symbolName).ToList();

You currently loop through _outputVariables , but if it's null this will give an error, because null does not have a .ToList() .您当前循环遍历_outputVariables ,但如果它为null则会出现错误,因为null没有.ToList() So you should add a ?所以你应该添加一个? after your _outputVariables , so it will return null instead of an exception when it's null.在您的_outputVariables ,因此当它为空时它将返回null而不是异常。

Same goes for X . X If X is null and you try to get the property symbolName , you will get an error, because null doesn't have a property called symbolName .如果Xnull并且您尝试获取属性symbolName ,则会出现错误,因为null没有名为symbolName的属性。 So you want to add a ?所以你想添加一个? here too.这里也。 So it will return null instead of an exception.所以它将返回null而不是异常。

Leaving you with: var recordList = _outputVariables?.ToList().Where(X => X?.symbolName == _symbolName).ToList(); var recordList = _outputVariables?.ToList().Where(X => X?.symbolName == _symbolName).ToList();你: var recordList = _outputVariables?.ToList().Where(X => X?.symbolName == _symbolName).ToList();

You can try this你可以试试这个

if(_outputVariables!=null)
{
var recordList = _outputVariables.Where(X => X.symbolName ==_symbolName).ToList();
}
if (recordList != null)
{
       //more coding...
}

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

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