Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension of StartsWith that searches in all words

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)

like image 924
sports Avatar asked Jan 13 '23 19:01

sports


1 Answers

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));
}
like image 154
p.s.w.g Avatar answered Jan 30 '23 12:01

p.s.w.g