簡體   English   中英

如何使用可能的空列表處理此LINQ代碼中的空值?

[英]How to handle nulls in this LINQ Code using a possible null List?

我正在使用MVC3,Razor,C#。

我有一些Razor代碼,其中包括一些LINQ。 它試圖從List中獲取值。 有時列表為空。 目前,該應用程序因此提出了一個空異常,即“myCustomers”為空。

編碼:

Model.myCustomers.First().Name

基本上“myCustomers”定義為:

public List<Customer> myCustomers

並填充“LINQ to Entity”查詢。

如果“myCustomers”為null,我如何確保剃刀代碼不會崩潰。 我不想為每個屬性寫很多“if(Name!= null)”類型塊。 由於布局設計問題,我無法遍歷所有屬性。 所以我需要改變:

Model.myCustomers.First().Name

某種程度上來說。

希望這個問題不要太混亂!

提前謝謝了。

編輯1

我喜歡不返回空值的邏輯,而是空列表。 我試過用類似的東西

return this._myCustomers ?? Enumerable.Empty<Customers>().ToList(); 

在Razor頁面的LINQ的一行中測試它是空的而不是在“IF”塊中是理想的。

編輯2

    public static TValue SafeGet<TObject, TValue>(
        this TObject obj,
        Func<TObject, TValue> propertyAccessor)
    {
        return obj == null ? default(TValue) : propertyAccessor(obj);
    }

所以:

   Model.myCustomers.FirstOrDefault().SafeGet(m=>m.Name)

對於最佳實踐,Collection或enumerable永遠不應返回null值。

一旦確保myCustomers不為null,您只需要檢查myCustomers的第一個項目是否為null。

var customer = Model.myCustomers.FirstOrDefault();
if (customer != null)
{
   var name = customer.Name;
}

由於布局設計問題,我無法遍歷所有屬性。

我不清楚這意味着什么,但你不能做這樣的事嗎?

@if (Model.myCustomers == null || !Model.myCustomers.Any())
{
    <p>No customer found.</p>
}
@else
{
    [ put the markup for each property here ]
}

如果您的收藏品不為null ,那么您可以在razon視圖中使用

 Model.myCustomers.Any() ? Model.myCustomers.First().Name : string.Empty;

如果由於某種原因你不能避免你的收集為空,我想你可以做這樣的事情。

 Model.myCustomers == null ? string.Empty : Model.myCustomers.Any() 
       ? Model.myCustomers.First().Name : string.Empty;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM