1

I need to get same matching name records.so that i am using the contains linq expression. ex : a.User.DisplayName.Contains(strDisplayName.Trim())

But if strDisplayname == "Andrew   Wodd", there are more spaces in between Andrew and Woddd, in which case it's getting the result.

How do I get that result if there is more than one space in the name?

Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
user3106578
  • 177
  • 1
  • 2
  • 12

4 Answers4

4

Use Regex.Replace and replace all multiple spaces with single space

var replaced = Regex.Replace(strDisplayName, @"\s+", " ");    
a.User.DisplayName.Contains(replaced);
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
2

You could do a Regular Expression to normalize whitespace:

Regex.Replace(input, "\s+", " ");
jessehouwing
  • 106,458
  • 22
  • 256
  • 341
1

Use the following:

strDisplayName = string.Join( " ", strDisplayName.Split( (char[])null, StringSplitOptions.RemoveEmptyEntries ) );

This will trim the same characters (not only space) as the Trim you already use

Panos Theof
  • 1,450
  • 1
  • 21
  • 27
  • +1 for avoiding regex. – David Martin Dec 20 '13 at 09:32
  • @DavidMartin why is that a good thing? This code isn't going to be faster or easier to understand. In fact, it will create multiple temporary strings for each search – Panagiotis Kanavos Dec 20 '13 at 09:38
  • Regex will create Match objects for each match, plus a List, plus a temporary string for each match, plus a StringBuilder (to join the results). So the intermediate objects created are at least doubled in the case of Regex. OTOH string.Join will calculate the length of the resulted string and it will use the FastAllocateString to create it – Panos Theof Dec 20 '13 at 09:47
  • 1
    @PanagiotisKanavos there are 3 answers all using regex, its always good to see alternative ways of achieving the same goal. I didn't/don't want to get into the regex good/bad debate, that wasn't my intention. There are plenty of discussions on that subject, but providing alternatives give developers more tools in their toolbag. – David Martin Dec 20 '13 at 10:03
0

To remove extra blanks in your displayname you could use a regex:

a => Regex.Replace(a.User.DisplayName, @"\s\s+", " ").Trim() == Regex.Replace(strDisplayName, @"\s\s+", " ").Trim()

Good luck with your quest.

Casperah
  • 4,504
  • 1
  • 19
  • 13
  • LINQ to Entities does not recognize the method 'System.String Replace(System.String, System.String, System.String)' method, and this method cannot be translated into a store expression. – user3106578 Dec 20 '13 at 10:34
  • _usersinapplicationroles.All().Where(a => a.ApplicationRoleId == iAppRoleId && (Regex.Replace(a.User.DisplayName, @"\s\s+", " ").Trim() == Regex.Replace(strDisplayName, @"\s\s+", " ").Trim())).AsQueryable(); getting error .can you please correct my expression – user3106578 Dec 20 '13 at 10:36