Linq is this string.Compare in the query inefficient and is there a better way?

12,418

Solution 1

public virtual User GetUser(string username)
        {
            return _db.Users.Single(x => x.UserName.ToLower() == username.ToLower());

        }

But I don't think the compare will be much slower though....

Solution 2

String.Compare is not in the list of functions supported by entity framework (see Supported Function List) This means that when you perform this query entity framework will retrieve the whole data set required to execute this compare and perform the compare locally. This will be very slow.

A much better solution is to use == to compare strings, for example:

return _db.Users.Single(x => x.UserName == username);

Solution 3

I would use String.Equals

return _db.Users.Single(x => 
          String.Equals(x.UserName, username, StringComparer.OrdinalIgnoreCase))

If i want to match "Martín" with "martin" (accent) as same, I would use String.Compare.

return _db.Users.Single(x => 
         string.Compare(x.UserName, username, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace);
Share:
12,418
AnonyMouse
Author by

AnonyMouse

please delete me

Updated on June 22, 2022

Comments

  • AnonyMouse
    AnonyMouse almost 2 years

    Originally I had this method:

    public virtual User GetUser(string username)
            {
                return _db.Users.Single(x => x.UserName == username);
            }
    

    So basically a linq method which gets a user based on the person's username.

    Trouble was I found that sometimes the username was coming through with an uppercase character at the start so it wasn't always working.

    So then I came up with:

    public virtual User GetUser(string username)
            {
                return _db.Users.Single(x => (string.Compare(x.UserName, username, true) == 0));
            }
    

    This works. However I get this must be really inefficient to do a string.Compare for the users?

    Is there a better way to write this without the string.Compare?