tags:

views:

380

answers:

3

I'm having problems with getting data using LINQ-to-SQL. I use the following piece of code to look up a user for our web app (user name is email address):

var referenceUser = 
    db.ReferenceUsers
      .SingleOrDefault(rf => rf.Email == values["emailAddress"]);

If I type [email protected] I get a ReferenceUser however if I type [email protected] I don't. How can I get LINQ to ignore the case when selecting a user?

+3  A: 

Does:

var referenceUser = 
    db.ReferenceUsers.SingleOrDefault(
        rf => rf.Email.ToLower() == values["emailAddress"].ToLower());

work?

The ToLower() should be translated into the correct SQL to run as a database query, and then return both results.

codekaizen
That's what I would do if I didn't know there was an ignore case flag, but +1 for idea.
David Brunelle
@David - how you compare matters in LINQ since the lambda expression sent to SingleOrDefault is translated. This way is sure to be translated into SQL.
codekaizen
Works good. However for other string compares that aren't in lambdas should i stick with ToLower() or should I use StringComparison.OrdinalIgnoreCase ??
Mike
@Mike - right, if you're running on the client side, you're better to use: `String.Equals(s1, s2, true)` or a `System.StringComparer` property which compares the way you want. Further, I think you'd rather use `InvariantCultureIgnoreCase` or `CurrentCultureIgnoreCase` instead of `OrdinalIgnoreCase` since the latter compares codepoint-to-codepoint instead of character-to-character.
codekaizen
Just be aware that calling .ToLower on the db column will ensure that even if it is indexed, SQL Server will not be able to use that index.Changing collation to a case-insensitive collation would be a better choice if the table is large enough to make a table scan a bad thing.
KristoferA - Huagati.com
+4  A: 
var referenceUser = db.ReferenceUsers.SingleOrDefault(rf => string.Compare(rf.Email, values["emailAddress"],true)==0);

Where the "true" is whether to ignore case or not

Program.X
Just as a point of consideration, I don't think this would run on the server, though. I recall using this pattern and not getting the query to be interpreted correctly.
codekaizen
Apparently by the way this answer is voted up, the SO readership is quite comfortable with .Net idioms, but less so with LINQ on IQueryable.
codekaizen
A: 

This is how I did it. Might give you a hint. I have a List with Profiles and I want to search for profilenames containing "aR", "Ar" or "AR".

List<Profile> profileList = CreateProfile();
string search = "aR".ToLower();

profileList = (from p in profileList where p.Name.ToLower().Contains(search)
        orderby p.Name select p).ToList();
Skylerr