是否有字符串的 StartsWith 扩展,它在字符串中的每个单词的开头进行搜索?
类似于:
"Ben Stiller".StartsWithExtension("Sti")
返回真值
我想要这个,这样我就可以为搜索做一个谓词。
假设有一个名为 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));
}
关于c# - 搜索所有单词的 StartsWith 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15722221/