Remove spaces in string before comparison

Qwark picture Qwark · May 13, 2011 · Viewed 7k times · Source

I want to get Contacts based on phone number, but in Ms Dynamics phone numbers are stored in all kinds of format like 123 45 678, 12 34 56 78, 0112345678, 01 12345678 and so on.

So I have to remove spaces in them before I do the comparison, I did try to use the Replace method on the string but that gave me an Illegal method error in runtime.

Do I really have to retrieve all the contacts and do another loop for the comparison, Or is there a way to "Clean" the string in the query?

string phone = "12345678";
var contacts = from c in orgContext.CreateQuery<Contact>()
    join a in orgContext.CreateQuery<Account>() on c.AccountId.Id equals a.AccountId
    where (c.Telephone1.Replace(" ", "").Contains(phone) || c.MobilePhone.Replace(" ","").Contains(phone))
   select new DynamicContact
   {
     ContactId = c.ContactId,
     FirstName = c.FirstName,
     LastName = c.LastName,
     ....and more...    
   };

Edit:

This is the Exception message :

Invalid 'where' condition. An entity member is invoking an invalid property or method.

Answer

Lloyd Powell picture Lloyd Powell · May 13, 2011

Use :

phone = phone.Replace(" ", ""); // Replaces whitespace with empty string

It's pretty much the same as what you're doing within the linq expression.