[英]Extension of StartsWith that searches in all words
是否有字符串的StartsWith的擴展,它在字符串中的每個單詞的開頭搜索?
類似於: "Ben Stiller".StartsWithExtension("Sti")
返回true
我想要這個,所以我可以做一個搜索的謂詞。
讓我們說有一個名為Persons的列表, ICollection<Person>
每個人都有一個屬性名稱,其值為“Ben Stiller”或“Adam Sandler”。
我希望能夠做如下的謂詞:
Persons.Where(p => p.Name.StartsWithExtension(query))
謝謝(歡迎其他更好的方法來實現這一目標)
您可以先按字詞拆分字符串,如下所示:
var result = "Ben Stiller".Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
.Any(x => x.StartsWith("Sti"));
當然你可以用你自己的擴展方法來編寫這個,如下所示:
public static bool AnyWordStartsWith(this string input, string test)
{
return input.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
.Any(x => x.StartsWith(test));
}
可能最簡潔的方法是使用正則表達式:
public static bool StartsWithExtension(this string value, string toFind)
{
return Regex.IsMatch(value, @"(^|\s)" + Regex.Escape(toFind));
}
這比在字符''上拆分源字符串更可靠,因為它可以處理其他空白字符。
為什么不創建一個“ToWords”方法,然后將結果提供給StartsWith?
事實上,“ToWords”已經存在:
編輯:對於咯咯笑,我們讓它在倍數上工作
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"));
那么你甚至可以這樣檢查:
bool flag = (sample_str.StartsWith("Sti" ) || sample_str.Contains(".Sti") || sample_str.Contains(" Sti"))
public static bool ContainsWordStartingWith(this string aString, string startingWith)
{
return aString.Split(' ').Any(w => w.StartsWith(startingWith));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.