2013-03-30 37 views
4

是否有字符串的StartsWith扩展名,它在字符串中的每个单词的开始处搜索?StartsWith搜索全部词的延伸

喜欢的东西: "Ben Stiller".StartsWithExtension("Sti")返回true

我想要这个,所以我可以做谓语进行搜索。

可以说有一个名单叫人,ICollection<Person>
每个人都有一个属性名称,像“本斯蒂勒”或“亚当桑德勒”的值。

我希望能够做谓语,如:

+0

如果姓氏具有其自己的含义 - 在这种情况下,您希望通过它进行搜索/过滤 - 将名称拆分为2个属性是有意义的 - 名字和姓氏(也许是全部名字,以便于打印/记录或任何你要做的人对象) –

+0

那么,最简​​单的(即使它不是“最好的”)方式可能是'Contains(“”+ str);'... – Carsten

+0

if(sample_str.StartsWith(“Sti”)|| sample_str.Contains(“。Sti”)|| sample_str.Contains(“Sti”))return true;' –

回答

6

您可以用文字分割字符串了

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)); 
} 
1

为什么不改为创建一个“ToWords”方法,然后将结果提供给StartsWith?

事实上,“毛诗补传”已经种存在:

编辑:于笑声,让我们有它的倍数工作

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")); 
0

那么你甚至可以检查它是这样的:

bool flag = (sample_str.StartsWith("Sti") || sample_str.Contains(".Sti") || sample_str.Contains(" Sti")) 
2

可能最简洁的方法是使用正则表达式:

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

这比分割字符''上的源字符串更可靠,因为它可以处理其他空格字符。

+0

+1。良好的解决方案,更灵活。 –

+0

此外,由于bcl正则表达式中固有的伪cacheiness,您可能会看到重复查询的性能提升(swag) – JerKimball

0
public static bool ContainsWordStartingWith(this string aString, string startingWith) 
    { 
     return aString.Split(' ').Any(w => w.StartsWith(startingWith)); 
    }