4

Is there an extension of string's StartsWith that it searches at the start of every word in the string?

Something like: "Ben Stiller".StartsWithExtension("Sti") returning true

I want this so I can make a predicate for searching.

Lets say there's a list called Persons, ICollection<Person>
Each person has a property Name, with values like "Ben Stiller" or "Adam Sandler".

I want to be able to do predicates like:

Persons.Where(p => p.Name.StartsWithExtension(query))

Thanks (Other better ways of achieving this are welcome)

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
sports
  • 7,851
  • 14
  • 72
  • 129
  • If the last name has a meaning of its own - in this case you want to search/filter by it - it would make sense to split the name to 2 properties - first name and last name (and maybe full name for easy printing/logging or whatever you'd do with the person object) – Honza Brestan Mar 30 '13 at 19:00
  • Well, the easiest (even if it's not the "best") way would probably be `Contains(" " + str);`... – Carsten Mar 30 '13 at 19:04
  • `if (sample_str.StartsWith("Sti" ) || sample_str.Contains(".Sti") || sample_str.Contains(" Sti")) return true;` – Parimal Raj Mar 30 '13 at 19:06
  • Do you need to use this with Linq-to-Sql or Linq-to-Entities? – p.s.w.g Mar 30 '13 at 19:06
  • @p.s.w.g Either way, this is not going to work: the method cannot be translated into SQL. It will only work in linq to objects. – Gert Arnold Mar 30 '13 at 19:27
  • @GertArnold **AppDeveloper**'s answer would work in SQL. I'm trying to determine exactly what kind of answer OP is looking for. Since OP didn't specify any additional constraints, most answers here assume the string is already in memory. – p.s.w.g Mar 30 '13 at 19:30
  • @p.s.w.g Sure, I understand why you ask. I clumsily tried to make the OP aware of the restrictions while making clear it had to do with your comment. – Gert Arnold Mar 30 '13 at 19:37
  • I would be awesome that it worked in Linq-To-Sql, for performance issues. But as I'm already using Linq-To-Entities, most of the answers here given are great – sports Mar 30 '13 at 20:53

5 Answers5

6

You can split the string up by words first, like this:

var result = "Ben Stiller".Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                          .Any(x => x.StartsWith("Sti"));

Of course you could write this as you're own extension method, like this:

public static bool AnyWordStartsWith(this string input, string test)
{
    return input.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                .Any(x => x.StartsWith(test));
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
2

Probably the most succinct approach is to use regex:

public static bool StartsWithExtension(this string value, string toFind)
{
    return Regex.IsMatch(value, @"(^|\s)" + Regex.Escape(toFind));
}

This is also more reliable than splitting the source string on the character ' ', since it can handle other whitespace characters.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Also, with the inherent pseudo-cachiness in the bcl regex , you might see a performance boost on repeated queries (swag there) – JerKimball Mar 31 '13 at 00:45
1

Why not instead create a "ToWords" method, then feed the results of that to StartsWith?

In fact, "ToWords" already kind of exists:

Edit: for giggles, let's have it work on multiples

 var someNames = new []{ "Sterling Archer", "Cyril Figgus" };
 var q = someNames
    .Select(name => name.Split(' '))
    .SelectMany( word => word)
     // the above chops into words
    .Where(word => word.StartsWith("Arch"));
JerKimball
  • 16,584
  • 3
  • 43
  • 55
0

Well you can even check it this way :

bool flag = (sample_str.StartsWith("Sti" ) || sample_str.Contains(".Sti") || sample_str.Contains(" Sti")) 
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
0
    public static bool ContainsWordStartingWith(this string aString, string startingWith)
    {
        return aString.Split(' ').Any(w => w.StartsWith(startingWith));
    }