Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT AS in Linq with WHERE clause

Tags:

c#

linq

I am trying to populate a drop down list with a Linq query. However, I need to have FirstName and Surname as one field. Concatenating in the DDL.DataTextField returns a field not found error.

SQL would be something like this:

SELECT (FirstName + SPACE + Surname) AS FullName FROM Table WHERE ID=1

Current Linq:

public IList<mytable> GetNames(int p_ID)
{
    return db.mytable.Where(c => c.ID_fk == p_ID).ToList();
}
like image 577
enigma20 Avatar asked Sep 25 '12 09:09

enigma20


2 Answers

You can use this, if you only need the full name:

public IList<string> GetNames(int p_ID)
{
    return db.mytable.Where(c => c.ID_fk == p_ID)
                     .Select(x => x.FirstName + " " + x.Surname)
                     .ToList();
}
like image 158
Daniel Hilgarth Avatar answered Oct 06 '22 02:10

Daniel Hilgarth


you could try this:

return db.mytable.Where(c => c.ID_fk == p_ID).Select(c=>c.FirstName + " " + c.Surname). ToList();

so you have a list of strings

like image 35
stefano m Avatar answered Oct 06 '22 00:10

stefano m