Andrei Dvoynos
Andrei Dvoynos

Reputation: 1145

Using .ToString inside a LINQ query select statement

I have the following LINQ to entities query (using odp.net):

Dim query = from Elemento in X.VIEW
            where Elemento.code = "10"
            Select New With {Elemento.code, .Time = Elemento.Time.ToString("HH:mm")}
query.ToList()

And the code throws an exception on the ToList() method:

LINQ to Entities does not recognize the method 'System.String ToString()'

I've read all over SO about this but haven't found an easy workaround.


Lazyberezovsky has the right answer, I couldn't get it to work before because I was doing this:

Dim query = (from Elemento in X.VIEW
            where Elemento.code = "10"
            Select New With {Elemento.code, Elemento.Time}).ToList
Dim query2 = from elemento in query
        Select New With {elemento.code, TIME = elemento.Time.ToString("HH:mm")}

Dim result = query2.ToList()

But this doesn't work, apparently you have to do it in a single step.

Upvotes: 4

Views: 2338

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

You can convert DateTime to string in-memory. Just make ToList call before converting time:

In C#:

var query = from Elemento in X.VIEW
            where Elemento.code == "10"
            select new { Elemento.code, Elemento.Time };

var result = query.ToList() // now you are in-memory
                  .Select(x => new { x.code, Time = x.Time.ToString("HH:mm") });

In VB.Net:

Dim query = From Elemento In X.VIEW
    Where Elemento.code = "10"
    Select New With {Elemento.code, Elemento.Time}

Dim result = query.ToList() _
    .Select(Function(x) New With {x.code, .Time = x.Time.ToString("HH:mm")})

BTW Why are you selecting Elemento.code into result, if you are filtering by it in where operator (it will always be equal to "10").

Upvotes: 7

Related Questions