2

我想以任何列的任何单词开头来搜索关键字。

例如,displayedCustomers 对象包含 Name,即 Sameer Singh。

所以当我的搜索变量

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 

我以前将此代码用于整个单词。但不知道拆分字符串的空间并与起始元素进行比较。请帮助以有效的方式做到这一点

4

3 回答 3

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
于 2012-10-31T08:44:12.533 回答
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);

演示:http: //ideone.com/mEh5Q1

您可以对记录中的每个单词或每一列执行此操作。

例如(假设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));
于 2012-10-31T08:42:27.597 回答
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")
{
    // ...
于 2012-10-31T08:46:49.647 回答