我想从任何列的任何单词开始搜索关键字。
例如displayedCustomers对象包含Sameer Singh的Name。
所以我的搜索变量
searchOption="eer" //it should not search,
searchOption="ingh" //it should not search,
searchOption="Sa" //it should search,
searchOption="Si" //it should search,
searchOption="ameer" //it should not search
我以前使用此代码作为整个单词。但是不知道分割字符串的空间并与起始元素进行比较。请以有效的方式帮助您做到这一点
答案 0 :(得分:3)
// Split the word by space
var split = str.Split(" ");
// Check if firstname or lastname starts with searchString
var found = split[0].StartsWith(searchString) || split[1].StartsWith(searchString);
如果你不知道这个人是否也有中间名,你也希望对此进行测试:
var searchString = "Sam";
var split = customerName.Split(" ");
var found = false;
foreach(var str in split)
{
found == found || str.StartsWith(searchString);
if(found)
break;
}
用方法包装:
public bool NameStartsWith(string name,string searchStr)
{
var split = name.Split(" ");
foreach(var str in split)
{
if(str.StartsWith(searchString))
return true;
}
return false;
}
像这样使用:
var matches = NameStartsWith("Sameer Singh","Sa"); // true
var matches = NameStartsWith("Sameer Singh","Si"); // true
var matches = NameStartsWith("Sameer Singh","S"); // true
var matches = NameStartsWith("Bobby Singer Bobberson","Sing"); // true
var matches = NameStartsWith("Sameer Singh","meer"); // false
答案 1 :(得分:2)
您可以使用String.StartsWith
string name = "Sameer Singh";
string searchOption = "eer";
bool nameStartsWith = name.StartsWith(searchOption);
Console.Write("{0} {1} {2}"
, name
, nameStartsWith ? "starts with" : "starts not with"
, searchOption);
您可以为记录中的每个字词或每个列执行此操作。
例如(假设DataRow
):
bool rowContains = row.ItemArray.Any(o => string.Format("{0}", o).StartsWith(searchOption));
假设String[]
:
bool arrContains = array.Any(str => str.StartsWith(searchOption));
假设String
:
bool nameContains = name.Split().Any(w => w.StartsWith(searchOption));
答案 2 :(得分:2)
您应该将String.StartsWith
与String.Split
一起使用:
public bool IsMatching(string Name, string SearchOption)
{
foreach (string s in Name.Split(' '))
{
if s.StartsWith(SearchOption)
return true;
}
return false;
}
// use it like:
if IsMatching("Sameer Singh", "Sa")
{
// ...