ElenaDBA ElenaDBA - 4 months ago 11
C# Question

Linq query concatenating two fields

var result = (from u in ctx.Users
where u.UserId.Equals(id)
select new
{
FullName = u.LName + ", " + u.FName
}).ToString();


I also tried

var result = ctx.Users.Where(u => (u.UserId.Equals(id)))
.Select( u => new {FullName=u.LName + ", " + u.FName})
.ToString();


But both return SQL Select statement, not a full name. Could anyone please help?

Answer

You are not executing the query. To execute the query, you need to call a special method like ToList(), First(), Single(), FirstOrDefault(), etc...

What you are doing is just creating a query. ToString would just give you a representation of such query.

Here is an example that uses First() to execute the query:

var result =
    ctx.Users
        .Where(u => u.UserId.Equals(id))
        .Select(u => u.LName + ", " + u.FName)
        .First();

I am using First because I assume you are selecting a specific user.

Or for your original code:

 var result = (from u in ctx.Users
                      where u.UserId.Equals(id)
                      select new
                      {
                          FullName = u.LName + ", " + u.FName
                      }).First();