2012-11-30 36 views
-2

这是我的代码示例。在wp7应用程序中比较字符串的麻烦

这里我从另一个页面收到一个字符串变量。在代码运行时

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
    { 
     base.OnNavigatedTo(e); 
     string newparameter = this.NavigationContext.QueryString["search"]; 
     weareusingxml(); 

     displayResults(newparameter); 

    } 

private void displayResults(string search) 
{ 
bool flag = false; 
try 
{ 
    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) 
    { 
     using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("People.xml", FileMode.Open)) 
     { 
      XmlSerializer serializer = new XmlSerializer(typeof(List<Person>)); 
      List<Person> data = (List<Person>)serializer.Deserialize(stream); 
      List<Result> results = new List<Result>(); 


      for (int i = 0; i < data.Count; i++) 
      { 
       string temp1 = data[i].name.ToUpper(); 
       string temp2 = "*" + search.ToUpper() + "*"; 
       if (temp1 == temp2) 
       { 
        results.Add(new Result() {name = data[i].name, gender = data[i].gender, pronouciation = data[i].pronouciation, definition = data[i].definition, audio = data[i].audio }); 
        flag = true; 
       } 
      } 

      this.listBox.ItemsSource = results; 

} 
catch 
{ 
    textBlock1.Text = "error loading page"; 

} 
if(!flag) 
{ 
    textBlock1.Text = "no matching results"; 
} 

} 

没有被加载到列表中,我刚刚得到的消息“没有匹配的结果。”

+0

你为什么要增加对TEMP2的*?你的Person.Name也包含*?或者您是否尝试进行包含搜索而不是完全匹配? – ryadavilli

回答

0

你检查过以确保data.Count > 0

1

看起来你正在尝试做一个包含搜索(我的猜测基础上的另外的*周围的搜索字符串。您可以删除“*”,并做了string.Contains比赛。

试试这个。

string temp1 = data[i].name.ToUpper(); 
string temp2 = search.ToUpper() 
if (temp1.Contains(temp2)) 
{ 
+0

非常感谢ryadavilli,它工作。 (*)应该是一张通配符 – user1865560

+0

很高兴帮忙。请标记为答案,如果这为你工作。 – ryadavilli

1

它看起来像你想检查是否一个字符串包含另一个(即字符串匹配),而不是它们是否相等

在C#中,你这样做是这样的:

haystack = "Applejuice box"; 
needle = "juice"; 
if (haystack.Contains(needle)) 
{ 
    // Match 
} 

或者,你的情况(和跳过*您添加到字符串TEMP2)

if (temp1.Contains(temp2)) 
{ 
    // add them to the list 
}