Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: custom column names

UPDATE

I'm basically binding the query to a WinForms DataGridView. I want the column headers to be appropriate and have spaces when needed. For example, I would want a column header to be First Name instead of FirstName.


How do you create your own custom column names in LINQ?

For example:

Dim query = From u In db.Users _
            Select u.FirstName AS 'First Name'
like image 950
Bryan Roth Avatar asked Sep 24 '08 16:09

Bryan Roth


1 Answers

As CQ states, you can't have a space for the field name, you can return new columns however.

var query = from u in db.Users
            select new
            {
                FirstName = u.FirstName,
                LastName = u.LastName,
                FullName = u.FirstName + " " + u.LastName
            };

Then you can bind to the variable query from above or loop through it whatever....

foreach (var u in query)
{
   // Full name will be available now 
   Debug.Print(u.FullName); 
}

If you wanted to rename the columns, you could, but spaces wouldn't be allowed.

var query = from u in db.Users
            select new
            {
                First = u.FirstName,
                Last = u.LastName
            };

Would rename the FirstName to First and LastName to Last.

like image 192
Scott Nichols Avatar answered Oct 12 '22 21:10

Scott Nichols