views:

4120

answers:

4
+8  Q: 

Linq int to string

Hi,

how do I cast and int into a string? None of the following do works:

from s in ctx.Services
    where s.Code.ToString().StartsWith("1")
    select s

from s in ctx.Services
    where Convert.ToString(s.Code).StartsWith("1")
    select s

from s in ctx.Services
    where ((string)s.Code).ToString().StartsWith("1")
    select s

EDIT

The error I get is:

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

+1  A: 

Here is a way to do it.

int[] x = new int[] {11,3,15,7,19};

var j = from s in x where s.ToString().StartsWith( "1") select s.ToString();

Console.WriteLine( j );
rp
this doesn't help him - he's using linq to entities
ShuggyCoUk
+7  A: 

Linq to Entities does not support as many conversion of functions to server hosted sql.

ToString (on anything) is one of them

Here's a post suggesting workarounds and here's the list of supported functions

This has been asked before on Stack overflow specifically asking how to convert an int to a string

ShuggyCoUk
A: 

I had a similar issue

        IQueryable<Street> query = db.Streets.AsQueryable();
        query = query.Where(street => street.Name.ToLower().StartsWith(keyword))
                        .Take(10)
                        .OrderBy(street => street.Name);

        var list = query.Select(street => new
        {
            street.StreetId,
            Name = street.Name + " " + street.Suburb.Name + " " + street.Suburb.State.Name + " " + street.Suburb.Postcode

        });

street.Suburb.Postcode was throwing 'cannot convert non primative type error' as its an int? After following shuggy's link I fixed by adding .AsEnumerable to force int? -> string conversion 'client side' i.e. LINQ to Objects. i.e.

var list = query.AsEnumerable().Select(street => new
        {
            street.StreetId,
            Name = street.Name + " " + street.Suburb.Name + " " + street.Suburb.State.Name + " " + street.Suburb.Postcode

        });
jboy
+1  A: 

With EF v4 you can use SqlFunctions.StringConvert. So your code would end looking like this:

from s in ctx.Services
where SqlFunctions.StringConvert((double)s.Code).StartsWith("1")
select s

EDIT

As Rick mentions in his comment, the reason for casting the int to a double (decimal probably works too) is that the function does not have an overload for int.

Brian
This worked for me! The only funny thing about this is that apparently there is no overload of this function for 'int'. That's why Brian is boxing this as a double before calling the function above. In my opinion this needs to be marked as the answer for this question.
Rick Arthur