2013-06-19 41 views
2

,這是我的行動:做一個列表項結果,反之亦然

public ActionResult List() 
     { 
      var currentDate = DateTime.Now; 
      var list = new List<ArchiveViewModel>(); 
      for (var startDate = new DateTime(2012, 11, 1); startDate <= currentDate; startDate = startDate.AddMonths(1)) 
      { 
       list.Add(new ArchiveViewModel 
       { 
        Month = startDate.Month, 
        Year = startDate.Year, 
        FormattedDate = startDate.ToString("MMMM, yyyy") 
       }); 
      } 
      return View("List",list); 
     } 

這就是查看這個動作的結果

@model IList<Blog.Web.UI.ViewModels.ArchiveViewModel> 

    @foreach (var item in Model) 
    { 

      @Html.ActionLink(item.FormattedDate, "Post", "Archive", new { month = item.Month, year = item.Year }, null) 

    } 

輸出是這樣

November, 2012 
December, 2012 
January, 2013 
February, 2013 
March, 2013 
April, 2013 
May, 2013 
June, 2013 

,但我想要在輸出這樣的東西

June, 2013 
    May, 2013 
    April, 2013 
March, 2013 
... 
November, 2012 

我該怎麼做?

+0

你是怎麼得到這個錯誤的? **不能將void分配給局部變量!** –

回答

1

您正在向後創建列表。您可以按其他人所描述的方式對其進行排序,也可以在第一時間正確完成。

public ActionResult List() 
     { 
      var currentDate = DateTime.Now; 
      var list = new List<ArchiveViewModel>(); 
      for (var startDate = currentDate; startDate >= new DateTime(2012, 11, 1); startDate = startDate.AddMonths(-1)) 
      { 
       list.Add(new ArchiveViewModel 
       { 
        Month = startDate.Month, 
        Year = startDate.Year, 
        FormattedDate = startDate.ToString("MMMM, yyyy") 
       }); 
      } 
      return View("List",list); 
     } 
2
var newList = list.Reverse(); //This will change the order of all records 

var newList = list.OrderByDescending(x => x.Year) 
        .ThenBy(x => x.Month) 
        .ToList(); 
+1

儘管兩個答案(@Nnp)都解決了這個問題,但這個問題更加清晰,並且有助於代碼可讀性。 – mgnoonan

0

變種newList = list.Reverse();

+0

不能將void分配給局部變量! –