Search code examples
c#sqllinq

Concatenate two column values in LINQ Lambda Expression


I have a table where there are two columns. First_Name and Last_name. I am populating a gridview using LINQ.

protected void Page_Load(object sender, EventArgs e)
    {
        myLinQtoSQLClassDataContext objDataContext = new myLinQtoSQLClassDataContext();

        var allUserList = from CurrentUser in objDataContext.Users.Where(c => c.Is_Deleted != false)                              
                          select new
                          {
                              CurrentUser.First_Name, 
                              CurrentUser.Last_Name,
                              CurrentUser.Email_ID,
                              CurrentUser.GUID
                          };

        GridView1.DataSource = allUserList;
        GridView1.DataBind();                              
    }

I can retrieve the values using LINQ, but I want to concatenate the first name and last name with a space in between.

The equivalent SQL query what I am trying to achieve would be like this:

Select First_name + ' ' + Last Name as Username, Email_ID, GUID
From tbl_Users where Is_Deleted != false

How can I achieve this through the lambda expression?


Solution

  • You can use string concatenation:

    select new
    {
        Username = CurrentUser.First_Name + " " + CurrentUser.Last_Name,
        CurrentUser.Email_ID,
        CurrentUser.GUID
    };