Linq int to string

Viewed 57540

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

9 Answers

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

        });

When using LINQ to Objects you can use the ToString() helper.

I tried this workaround and it worked for me:

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

Hope this helps

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 );
Related