How to use string.Format with LINQ Select

When I project new data types using the Select operator I sometimes want to create new strings from the combination of existing properties.  Naturally I turn to string.Format.  However, if you attempt a call like the one below:

public object Get(int id)
{
   return this.db.People.Where(p => p.Id == id)
                                        .OrderBy(p => p.LastName)
                                        .Select(p => new { FullName = string.Format(“{0} {1}”, p.FirstName, p.LastName) })
                                        .ToArray();
}

I will get the following error:

"LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object, System.Object)' method, and this method cannot be translated into a store expression."

The problem is everything that happens before the .ToArray() is parsed and turned into a command that can be sent to the data source.  However, LINQ nor would the data source have any idea what to do with System.String.Format.

There is a very simply solution.  Simply call .ToArray() before you use the Select operator.

public object Get(int id)
{
   return this.db.People.Where(p => p.Id == id)
                                        .OrderBy(p => p.LastName)
                                         .ToArray()
                                        .Select(p => new { FullName = string.Format(“{0} {1}”, p.FirstName, p.LastName)});
}

 

That simply change will perform the select after the results have been retrieved from the data source.

Comments are closed