add a string list to a viewmodel list

1.6k views Asked by At
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);
    }
}

the code above creates a list of the top 5 news items ordered by date descending, I have created two lists one is a list of URLs called urlList and another which contains the news items called newsModel.

urlList is a list of strings and newsModel is a list of the NewsManagerViewModel, in each list there are exactly 5 elements.

I am looking for a way of combining these two lists so that each URL is matched with each news item.

currently if I combine the lists using newsModel.AddRange(urlList) all of the news items have the same id at the end (4) whereas my requirement is for the first news item to have id of 0 and the last an id of 4.

Any suggestions would be very much appreciated.

1

There are 1 answers

0
adricadar On BEST ANSWER

Instead of creating them separately, you can create them at once in a single 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);
    }
}