Why is this IndexOf call returning -1?

≯℡__Kan透↙ 提交于 2019-12-24 15:26:50

问题


I understand that IndexOf returns -1 when the parameter isn't found, but this doesn't make sense to me.

I have this code that iterates over all the DevExpress Checkboxes on my form, checks to see what their tag is, and tries to find it in the "filter" parameter that was passed to the method. If the tag is found in the filter, it should check that checkbox. It is always equating to false.

    public void FilterChanged(Control.ControlCollection controls, string filter)
    {
        filter = filter.Replace("[", String.Empty);
        filter = filter.Replace("]", String.Empty);

        foreach (Control control in controls)
        {
            if (control is CheckEdit && control.Tag != null)
            {
                var c = (CheckEdit)control;
                var cFilter = c.Tag.ToString();
                cFilter = cFilter.Replace("(", String.Empty);
                cFilter = cFilter.Replace(")", String.Empty);

                if (filter.ToUpper().IndexOf(c.Tag.ToString().ToUpper()) >= 0)
                    c.Checked = true;
                else
                    c.Checked = false;
            }
        }
    }

I set a breakpoint on my inner IF statement, and in my Immediate Window I entered the following:

filter.ToUpper().IndexOf(c.Tag.ToString().ToUpper()) = -1

filter.ToUpper() = "FILE NOT LIKE '%VERSIONINFO.CS%'"

cFilter.ToUpper() = "FILE NOT LIKE '%VERSIONINFO.CS%'"

Those look like pretty much the exact same thing, so shouldn't it be returning 0?

I cannot use equals because the filter might include multiple clauses, and thus wouldn't be equal.


回答1:


cFilter.ToUpper() = "FILE NOT LIKE '%VERSIONINFO.CS%'"

Those look like pretty much the exact same thing, so shouldn't it be returning 0?

But you are using c.Tag.ToString() instead of cFilter.ToUpper().

So this should work as expected:

if (filter.ToUpper().IndexOf(cFilter.ToUpper()) >= 0)
    c.Checked = true;
else
    c.Checked = false;

Note that you should use StringComparison.OrdinalIgnoreCase instead in IndexOf

c.Checked = filter.IndexOf(cFilter, StringComparison.OrdinalIgnoreCase) >= 0;


来源:https://stackoverflow.com/questions/19683295/why-is-this-indexof-call-returning-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!