ErocM
ErocM

Reputation: 4662

how do I handle spaces in peoples name when I run a query

I am running the following query:

if (!string.IsNullOrWhiteSpace(accountHolderName))
{
  Customer  cust = _entities.Customers.FirstOrDefault(c => c.AccountId == acct.AccountId &&
                                                     c.CorporationId == token.CorporationId &&
                                                     c.Name.ToUpper().StartsWith(accountHolderName.ToUpper()));
}

The record that I'm searching for has the Name of 'MC CARTAN'.

What the customer is actually putting is 'MCCARTAN'. So, it's not getting any results.

Is there a way to query and ignore spaces in the name?

On a side note, can I ignore case also?

Thanks!

Upvotes: 0

Views: 75

Answers (5)

Hugo S. Mendes
Hugo S. Mendes

Reputation: 1086

Try to use

accountHolderName.Replace(" ", "%").ToUpper()

Upvotes: 1

AWinkle
AWinkle

Reputation: 673

Your code should already handle casing (use of ToUpper), by using the Replace function to replace a space with no space, it should take care of that as well.

 if (!string.IsNullOrWhiteSpace(accountHolderName))
    {
      Customer  cust = _entities.Customers.FirstOrDefault(c => c.AccountId == acct.AccountId &&
                                                         c.CorporationId == token.CorporationId &&
                                                         c.Name.Replace(" ","").ToUpper().StartsWith(accountHolderName.Replace(" ","").ToUpper()));
    }

Upvotes: 1

Joshua Frank
Joshua Frank

Reputation: 13848

You could make a routine in the database to normalize the names, for instance by removing all spaces, and a corresponding one in C#, and then compare the normalized versions.

Customer  cust = _entities.Customers.FirstOrDefault(c => c.AccountId == acct.AccountId &&
                                                 c.CorporationId == token.CorporationId &&
                                                 c.Name.Normalize().StartsWith(Normalize(accountHolderName));

This link talks all about custom functions in the database.

If the cleanup that you need to do on the names is limited to simple string operations that LINQ already supports in the database, then you can do as the other answers suggest and just use those. I was trying to address the case where the string operations aren't as straightforward

Upvotes: 1

Vitor Costa
Vitor Costa

Reputation: 114

If you want to ignore all the spaces, then probably you should replace them by nothing:

name = name.Replace(" ", "");

To ignore the case, then you should do like this:

name.Equals(other_name, StringComparison.InvariantCultureIgnoreCase);

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

LINQ to Entities supports string.Replace() instance method, so you can try following:

c.Name.Replace(" ", "").ToUpper().StartsWith(accountHolderName.ToUpper())

Upvotes: 1

Related Questions