Casey Crookston Casey Crookston - 1 year ago 147
ASP.NET (C#) Question

Concatenate strings inside a linq 'select new object {

I need to join together two columns inside a LINQ select statement, like this:

var result = (from i in db.MyTable
blah blah ...
select new MyObject
Id = i.MyTableId,
ReportedByName = ub.FirstName + ' ' + ub.LastName

As I thought it might,
ub.FirstName + ' ' + ub.LastName
throws an error. How would I work this syntax?


Answer Source

You are currently concatenating a string with a char value while what you want is to concatenate strings. the string + operator is expeciting another string and not a char. use " " instead:

ReportedByName = ub.FirstName + " " + ub.LastName

Of course other ways way be:

  1. string.Format or C# 6.0 syntactic sugar for it of string interpolation.

    ReportedByName = string.Format("{0} {1}", ub.FirstName, ub.LastName)
    ReportedByName = $"{ub.FirstName} {ub.LastName}" //syntactic sugar of option above
  2. string.join (which is what I'll go for if you have more values)

    ReportedByName = string.Join(" ", ub.FirstName, ub.LastName)
  3. string.Concat

    ReportedByName = string.Concat(ub.FirstName, " ", ub.LastName)

Because you are in a linq to entities and not objects in memory the string.Join (and thus also string interpolation) and string.Format might not work if you are in a linq that is translated to an sql query. If you want to use those options first retrieve the items to memory (using ToList()/AsEnumerable() and then use them to concatenate the strings. See Jon's answer

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download