2012-02-24 105 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,然后访问我知道的正确值。

相关问题