blog.mha.dk
The on-line blog of Michael Holm Andersen

LINQ Projection and SelectListItem

Sunday, 17 January 2010 15:16 by mha

A small example of where LINQ Projection might come in handy is when you’re working with MVC. In the below example LINQ Projection is used to transform a enumeration of EmployeeCategory instances into an enumeration of SelectListItem instances:

var rep = new mhaRepository();
var person = rep.GetPersonByID(id);
ViewData["EmployeeCategories"] = from c in rep.EmployeeCategories
                         select new SelectListItem
                         {
                             Text = c.Name,
                             Value = c.ID.ToString(),
                             Selected = (c.ID == person.CategoryID)
                         };

In the View all that is needed to render the DropDownList is this:

<%= Html.DropDownList("EmployeeCategories") %>

Categories:   LINQ | ASP.NET MVC
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed
Comments are closed