2012-02-24 56 views
1

我得到List的產品,我需要從列表中獲得具有特定產品Id的項目,我從querystring參數中獲得Id。不過,我可能並不總是有一個產品Id傳給我。如果我沒有產品Id,則需要默認使用列表中的第一個產品。如果FirstOrDefault返回null,則返回列表中的第一個項目

目前我有:

@Model.Products.FirstOrDefault(x => x.Id == productId); 

這只是選擇產品與特定Id,如果沒有一個,它會默認爲null

有沒有辦法實現我想要的?

回答

7

這聽起來像你想:

var product = productId == null ? Model.Products.FirstOrDefault() 
        : Model.Products.FirstOrDefault(x => x.Id == productId); 
... 
@product 

,或者你可能意味着:

@(Model.Products.FirstOrDefault(x => x.Id == productId) ?? 
      Model.Products.FirstOrDefault()) 
+0

+1我想我更喜歡你的答案的第二部分過我(在現實中,我可能會代碼它就像這樣,特別是如果我知道我將不得不維持它,但我曾與那些說「像WTF這樣的雙重問號意味着什麼?」的人一起工作,所以有時候阻力最小的路徑是最簡單的。 )。 – 2012-02-24 10:55:55

+0

工作很好,謝謝。 – 2012-02-24 11:00:17

0

嘿檢查這一點,可以幫助你

MSDN鏈接:http://msdn.microsoft.com/en-us/library/bb340482.aspx

List<int> months = new List<int> { }; 

      // Setting the default value to 1 after the query. 
      int firstMonth1 = months.FirstOrDefault(); 
      if (firstMonth1 == 0) 
      { 
       firstMonth1 = 1; 
      } 
      Console.WriteLine("The value of the firstMonth1 variable is {0}", firstMonth1); 

      // Setting the default value to 1 by using DefaultIfEmpty() in the query. 
      int firstMonth2 = months.DefaultIfEmpty(1).First(); 
      Console.WriteLine("The value of the firstMonth2 variable is {0}", firstMonth2); 

      /* 
      This code produces the following output: 

      The value of the firstMonth1 variable is 1 
      The value of the firstMonth2 variable is 1 
      */ 
1

,如果你嘗試這樣的事情會發生什麼?

@if (productId != null) // assuming it's nullable 
{ 
    @Model.Products.FirstOrDefault(x => x.Id == productId) 
} 
else 
{ 
    @Model.Products.FirstOrDefault() 
} 

我知道這可能看起來有點麻煩,但它是很清楚它在做什麼(認爲如果別人要維護它),它應該工作。

但實際上我可能寧願將它設置爲ViewModel,然後訪問我知道的正確值。

相關問題