Looping the Query

Now, we already have List variable (genreList) and List from query (genres). The idea is looping through all items in genres, then perform some conditions, if any, before store it into genreList.

foreach (var genreItem in genres)
{
    genreList.Add(new GenreModel()
    {
        Id = genreItem.Id,
        Name = genreItem.Name
    });
}

Finally, return the collection to view.

return View(genreList);

Our final code will be look like this.

public ActionResult Index()
{
    IList<GenreModel> genreList = new List<GenreModel>();
    var query = from genre in context.Genres select genre;

    var genres = query.ToList();
    foreach (var genreItem in genres)
    {
        genreList.Add(new GenreModel()
        {
            Id = genreItem.Id,
            Name = genreItem.Name
        });
    }
    return View(genreList);
}

results matching ""

    No results matching ""