簡體   English   中英

如何解決 C# 中 linq 的 lambda 表達式中的對象引用錯誤?

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

我正在研究 WPF 應用程序。 在其中我試圖根據需要的條件從列表中獲取記錄。 但是當沒有找到任何記錄時,它會給我對象引用未找到錯誤。

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

所以如代碼所示,當 _outputVariables 根據 _symbolName 沒有任何記錄匹配時,它會給出Object reference not set to an instance of an object.'錯誤Object reference not set to an instance of an object.' X was null. . 那么我該如何處理這個問題呢? 請幫忙。

使用 C#6 中引入的空條件運算符(並且不要多次調用ToList() ):

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

你也可以像下面一樣使用

 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();

您當前循環遍歷_outputVariables ,但如果它為null則會出現錯誤,因為null沒有.ToList() 所以你應該添加一個? 在您的_outputVariables ,因此當它為空時它將返回null而不是異常。

X 如果Xnull並且您嘗試獲取屬性symbolName ,則會出現錯誤,因為null沒有名為symbolName的屬性。 所以你想添加一個? 這里也。 所以它將返回null而不是異常。

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

你可以試試這個

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