2012-12-13 16 views
0

我對C#很新,但是我需要更改一個查看數組的小函數。在我正在處理的代碼中,foreach用於瀏覽項目數組並將它們作爲列表項呈現在網頁上。現在,我必須找到像這樣的各種代碼塊,並將它們更改爲不循環整個數組,但挑選特定的項目並渲染它們。C#「First」類語句在調用數組時替換foreach

如果我只想拉出數組中絕對最新的項目,我該怎麼做?的我需要改變什麼 例子:#foreach($product in $Website.Products)需要被改變成類似#firstitem($product in $Website.Products)

這裏是上下文整個塊:

<div class="slider-content"> 
     #if($Website.Products.Count != 0) 
     <ul class="slider-list"> 
      #foreach($product in $Website.Products) 
      <li class="slider-page"> 
       <div class="vdd-container"> 
        <div class="vdd"> 
         <blockquote> 
          <span class="quote-open"></span> 
          <q><span>${product.Message}</span></q> 
          <span class="quote-close"></span> 
         </blockquote> 
        </div> 
       </div> 
       <cite> 
        <strong class="pnx">${product.Name}</strong> 
       </cite> 
      </li> 
      #end 
     </ul> 
     #else 
     <div class="not-found">No products in store.</div> 
     #end 
    </div> 

再次,只是在需要輸出的第一個項目,而不是循環和做每一個。

謝謝。

+0

爲什麼你的C#陣列開始'$'秒的條件? –

+0

你能提供更多信息嗎?你的循環體是什麼樣的?這是什麼View Engine? –

+0

@Sam我是我自己做這個小小的改變。所有與我合作的東西早在我被要求值得使用之前就已經存在了。 – user1729506

回答

1

您應該可以通過多種方式來完成此操作。

  1. 可以使用陣列存取:$Website.Products[0]
  2. 可以使用LINQ:用簡單的陣列工作時 $Website.Products.First()

第一個選項是更有效的。後面的選項在某些情況下看起來更好,如果使用某些類型的集合(而不是簡單的數組),性能可能會更好。


您的模板語法意味着您正在使用nVelocity模板引擎。如other SO questions中所述,nVelocity似乎無法處理擴展方法。由於First()是擴展方法,這意味着你不能使用它。

數組訪問器應該可以工作。

+0

我試過'$ Website.Products.First()'並且出現錯誤。我擔心我弄亂了語法。在後面的代碼中,因爲他們遍歷這個數組並將所有內容分配給$ product,所以有一點讀到' $ {product.Message}'因爲我放棄數組只是調用第一項,所以我會把'$ {Website.Products.First()。Message}'? – user1729506

+0

@ user1729506如果你能發佈你得到的錯誤,這將是有幫助的。 –

+0

只是沒有得到所需的輸出。發生錯誤,但沒有有效的調試信息自卸車可以給我顯示數據。道歉。 – user1729506

2

查看LINQ First()和/或FirstOrDefault()擴展方法。他們讓你得到任何IEnumerable<T>中的第一個項目。您還可以指定必須滿足

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.first.aspx

//Gets the first product in the Products collection 
var firstProduct = Website.Products.First(); 

//Gets the first product where a given condition is true 
var firstExpensiveProduct = Website.Products.First(p => p.Cost > 100);