Jibin Mathew Jibin Mathew - 1 month ago 7
C# Question

LINQ Select formatted values as a LIST

I am trying to fetch a column value and convert it as a list of formatted string value and I tried the below code

List<string> _names = (from p in context.RakHolders select
string.Format("{0},{1}", p.Name.Split(',')[0].Trim(), p.Name.Split(',')[1].Trim()))
.ToList();


My intention is to get a list of names with no unwanted space between commas in the column Name

I am getting exception while executing this line as


An exception of type 'System.NotSupportedException' occurred in
EntityFramework.SqlServer.dll but was not handled in user code

Additional information: 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.


How can I make this work [get a list of formatted column values] with LINQ

Answer
List<string> _names = (from p in context.RakHolders select p.Name)
    .ToList()
    .Select(name => name.Split(','))
    .Select(nameSplitted => string.Format("{0},{1}",  nameSplitted[0].Trim(), nameSplitted[1].Trim() ))
    .ToList();

Explanation: 'string.Format' cannot be translated to SQL so firstly we need to materialise the list with a first 'ToList()' (here we get the list of names, it's much more efficient than materialising full entities). Having the list in the memory you can transform it to the form you require.