简体   繁体   中英

Remove spaces in string before comparison

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.

Use :

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

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

String.Join("", yourString.Split(" "))

This will split on all spaces anywhere in the string and rejoin the resulting array without spaces. I believe this is what you are looking for.

Don't know if it's more or less efficient that String.Replace, but

new System.String(oldString.Where(x => !Char.IsWhiteSpace(x))); 

will strip out all the whitespace chars.

Replace your .Contains with .Equals . I am not sure if your provider supports String.Contains , but that could possibly cause your error. Despite the fact, that it does not make a lot sense to classify "0123 1234" as a match for "231".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM