views:

16

answers:

1

Whats the use of using custom comparers in Linq queries? Are they beneficial or are they just an overload on the server.

So i am talking about queries like

IEnumerable<Class> GetMatch(Class comparerObject)
{
  return  Session.Linq<Class>().Where(x=>new StringComparer<Class>().Equals(x,comparerObject))
}

and this is how my stringcomparer class looks like

public class StringComparer<T> : IEqualityComparer<T>
    where T : class, IStringIdentifiable
{
    public bool Equals(T x, T y)
    {
        if (x == null && y == null)
            return true;

        if (x == null || y == null)
            return false;

        return x.Id.Equals(y.Id, StringComparison.OrdinalIgnoreCase);
    }

So I was wondering how is this query run against the db? I think linq handles this internally where in it sends a request to the db only after all the cases in the comparere are run.

Edit:

Well if you are finding it hard to believe that the above will not work then take a simple example like

return  Session.Linq<Class>().Where(x=>x.Id.Equals(comparerObject,StringComparison.InvariantCultureIgnoreCase))

Then what do you think is the expected behavior?

Thanks.

+1  A: 

For LINQ to SQL, I'd expect that to fail at execution time - the query translator won't know what to do with your StringComparer<T> class.

In the case you've given, you should just use:

string idToMatch = comparerObject.Id;
return Session.Linq<Class>().Where(x => x.Id == idToMatch);

More complicated cases may or may not be feasible depending on exactly what you want to achieve.

Jon Skeet
I was under the impression that if Linq doesn't know how to translate a given piece of code into SQL it'll just pull all the data without that condition and apply it on the in-memory collection instead of failing at execution time? Or am I thinking of something unrelated?
R0MANARMY
@R0MANARMY: You can make it do that if you want by calling AsEnumerable, but it won't do it by default.
Jon Skeet
Thank you for clarifying that, will have to remember IQueryable doesn't like things it can't translate.
R0MANARMY
well I use it in my apps and it works. there is no problem at all..
well I am editing my post.. tell me what happens then