I’m using .toString() inside of linq – does it caching the converted value or does repeatedly converting it on each pass of the cycle?

The code example:

var id = 2;
var result = data.Where(x => x.SomeField.Any(p => p.Id == id.ToString()))

It seems it is converting int to string on each pass of the cycle:

enter image description here

Where I can check this type of behavior, to be sure?

  • I’m surprised by the answers, didn’t know that. When you use Linq queries in database calls, only one query is sent to the server, treating id.ToString() as a constant value. The solution is of course to put the string value in a variable.

    – 




  • Well, there’s no way that query could be translated to SQL, so it would have to be done in memory and .ToString() would be called each time.

    – 

  • @DStanley: Unless you cache it in a variable (since it wont change).

    – 

I made a test and it appears to call ToString for each item in data. I modified the code and used a special class below.

public class SpecialInt
{
    public int Value { get; set; }
    public static implicit operator int(SpecialInt x)
    {
        return x.Value;
    }
    public override string ToString()
    {
        Console.WriteLine("ToString is called");
        return Value.ToString();
    }
}

Then I ran the code below

var id = new SpecialInt { Value = 2 };
var result = data.Where(x => x.SomeField.Any(p => p.Id == id.ToString())).ToList();
Console.WriteLine(result.Count);

data contained two objects complying with the predicate.

Output was

ToString is called
ToString is called
2

The above behavior makes sense. Basically Where is a loop and an instruction is executed for each object. ToString is also an instruction and the runtime must execute it each time since the return value could change.

Leave a Comment