繁体   English   中英

在 wp7 应用程序中比较字符串时遇到问题

[英]trouble comparing strings in wp7 application

这是我的代码示例。

在这里,我从另一个页面收到一个字符串变量。

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";
}

}

运行代码时,列表中没有加载任何内容,我只收到消息“没有匹配的结果”。

看起来您正在尝试进行包含搜索(我的猜测基于您在搜索字符串周围添加 * 的猜测。您可以删除 '*' 并进行 string.Contains 匹配。

尝试这个。

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

看起来您正在尝试检查一个字符串是否包含另一个字符串(即子字符串匹配),而不是它们是否相等。

在 C# 中,你这样做:

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

或者,在您的情况下(并跳过您添加到字符串 temp2 的*

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

您是否检查过以确保data.Count > 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM