2015-06-18 106 views
1
public ActionResult LatestNews() 
{ 
    using (NDTMS2UtilsEntities newsEntities = new NDTMS2UtilsEntities()) 
    { 
     var newsItems = newsEntities.News.OrderByDescending(ni => ni.DateCreated).Take(5); 

     int n = 0; 
     var urlList = new List<string>(); 
     var newsModel = new List<NewsManagerViewModel>(); 

     while (n < newsItems.Count()) 
     { 
      string newsUrl = 
       new Uri(Request.Url.Scheme + "://" + Request.Url.Host + ":3153/News/Index/" + n).ToString(); 

      urlList.Add(newsUrl); 

      n++; 
     } 
     newsModel = newsItems.Select(item => new NewsManagerViewModel() 
     { 
      Title = item.Title, 
      NewsContent = item.NewsContent, 
      DateCreated = (DateTime) item.DateCreated 
     }).ToList(); 

     return PartialView(newsModel); 
    } 
} 

上面的代碼創建日期降序排列前5名的新聞項目的名單,我已經創建了兩個表一個是URL列表稱爲urlList,另一個包含新聞稱爲newsModel的項目。字符串列表添加到視圖模型列表

urlList是字符串列表和newsModelNewsManagerViewModel的列表,在每個列表中有5個元素。

我正在尋找一種方法來組合這兩個列表,以便每個URL都與每個新聞項匹配。

目前,如果我用結合所有newsModel.AddRange(urlList)新聞項目有相同的ID列表末(4),而我的要求是,第一條新聞有0 ID和4

最後一個id

任何建議將非常感激。

回答

2

與其單獨創建它們,您可以一次在一個for中創建它們。

public ActionResult LatestNews() 
{ 
    using (NDTMS2UtilsEntities newsEntities = new NDTMS2UtilsEntities()) 
    { 
     var newsItems = newsEntities.News.OrderByDescending(ni => ni.DateCreated).Take(5).ToList(); 

     var newsModel = new List<NewsManagerViewModel>(); 

     for(int n = 0; n < newsItems.Count(); n++) 
     { 
      string newsUrl = new Uri(Request.Url.Scheme + "://" + Request.Url.Host + ":3153/News/Index/" + n).ToString(); 
      var item = newsItems[n]; 
      var newsManagerModel = new NewsManagerViewModel() 
      { 
       Title = item.Title, 
       NewsContent = item.NewsContent, 
       DateCreated = (DateTime) item.DateCreated, 
       NewsUrl = newsUrl // add the url 
      } 
      newsModel.Add(newsManagerModel) 
     } 

     return PartialView(newsModel); 
    } 
}