Casey Crookston
Casey Crookston

Reputation: 13955

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
                }).First();

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

Thanks!

Upvotes: 1

Views: 7856

Answers (2)

Gilad Green
Gilad Green

Reputation: 37299

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

Upvotes: 3

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30205

If you use C#6 you can do that:

= $"{ub.FirstName} {ub.LastName}"

I think string interpolation is the easiest to read.

Upvotes: 2

Related Questions