LINQ Basic Projection

Author: Miguel Posted 5. May 2013

Here is a basic example of LINQ Projection.

I'm using it to build up a SelectList used in a dropdown for my ASP.NET MVC View.

In this particular case, I want to display all the administrators in my system in a dropdown for the user to select. I have a class that holds a particular users' information as well as a stored procedure that retrieves all the users in the database.
I then load these users into a List of my [User] class and convert it to a SelectList using LINQ.
The LINQ that I use makes easy work of creating and joining the [FirstName] and [LastName] fields to create a composite field to display in my dropdown.

My User class looks like this:

public class User
            public int UserId { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string RoleName { get; set; }

And I want my dropdown to look like this:

Here's the LINQ to project (read transform) my List<User> to a new list of a custom type where the FirstName and LastName properties are merged into a single Username property.

var userList =
                from u in users
                where u.RoleName == "Administrator"
                select new { Id = u.UserId, Username = string.Format("{0} {1}", u.FirstName, u.LastName) };

Next, I create a new SelectList passing in the my List, set the Value field (within the list) and the Display field and pass it to my view. Voila! :)

SelectList list = new SelectList(userList, "Id", "Username");

In LINQ, the process of transforming the results of a query is called projection. It is achieved using LINQ's select operator and can be applied in two 'styles', LINQ query syntax or LINQ method syntax. If I had've done this using method syntax it would've looked like this:

var userList = users.Where(u => u.RoleName == "Administrator")
                                .Select(u => new { Id = u.UserId, Username = string.Format("{0} {1}", u.FirstName, u.LastName) });

It all depends on your personal preference and the complexity of what you're trying to do. But in essence it's doing the same thing. I threw in the where operator so you could see how you could filter your items as well.

Hope this helps.


Global ASP.NET Hosting Leader - Click Here

Add comment

  Country flag

  • Comment
  • Preview

Global ASP.NET Hosting Leader - Click Here