简体   繁体   中英

C# NET String.Compare issue

I am working on some homework for class, and decided to add some extra stuff, and wound up confusing myself a bit. I have tried various comparison methods, and none of them seem to work, but I don't understand why.

Basically when an order is added to the system, it creates an instance of the class 'OrderInfo', and adds it to an ArrayList. In my code, I am using a foreach() loop to find the class instance that matches which entry in the ListBox they clicked, but something is wrong.

private void ordersListBox_DoubleClick(object sender, EventArgs e)
{
    if (ordersListBox.SelectedItem != null)
    {
        foreach (OrderInfo i in ordersList)
        {
            if (String.Compare(i.GetClientName(), ordersListBox.ToString(), true) == 0)
            {
                MessageBox.Show(i.GetClientName());
                break;
            }
        }
    }
}

Instead of

 if (String.Compare(i.GetClientName(), ordersListBox.ToString(), true) == 0)

try

 if (String.Compare(i.GetClientName(), ordersListBox.SelectedValue.ToString(), true) == 0)

You can also try this one.

 if (String.Compare(i.GetClientName(), ordersListBox.SelectedValue.ToString(), StringComparison.InvariantCultureIgnoreCase) == 0)
        {
            MessageBox.Show(i.GetClientName());
            break;
        }

For String comparisons it is better to use the Equals() method.

private void ordersListBox_DoubleClick(object sender, EventArgs e)
{
    if (ordersListBox.SelectedItem != null)
    {
        foreach (OrderInfo i in ordersList)
        {
            if (i.GetClientName().Equals(ordersListBox.ToString()))
            {
                MessageBox.Show(i.GetClientName());
                break;
            }
        }
    }
}

String.Compare returns a number, not a boolean.
The number will be positive, negative, or zero, depending on the relative alphabetical ordering of the strings.

You should call String.Equals , and pass StringComparison.OrdinalIgnoreCase .

I doubt you really want to compare the string representation of the ordersListBox to some sensible string.

The default implementation of ToString() of any object is to output the name of the type of the instance. The ordersListbox most likely is doing just that. You will want to consult the SelectedValue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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