2012-02-24 2 views
1

제품의 List을 얻었으므로 쿼리 문자열 매개 변수에서 얻은 특정 제품 Id으로 목록에서 항목을 가져와야합니다. 그러나, 나는 항상 제품이 Id 나에게 전달되지 않을 수 있습니다. Id 제품이 없으면 목록에서 첫 번째 제품을 기본값으로 사용해야합니다. 순간 FirstOrDefault가 null을 반환하면 목록의 첫 번째 항목을 반환하십시오.

나는이 : 그것은 null을 기본값으로 하나가없는 경우

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

이 단지 특정 Id으로 제품을 선택합니다.

내가 원하는 것을 얻을 수있는 방법이 있습니까?

답변

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는 두 가지 물음표를 의미 하는가?"와 같은 말을하는 사람들과 일했다. 그래서 때때로 최소한의 저항의 길은 가장 쉽다.). –

+0

그 덕분에, 고마워. –

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에 설정하고 올바르다는 것을 알고있는 값에 액세스합니다.

관련 문제