开发者

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 fo开发者_C百科rmat 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".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜