Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional OR never works when comparing two strings

I have a DataTable with some basic address information. I am trying to remove any states that are not New York or Pennsylvania.

So, this works fine:

foreach (DataRow row in uwDataTable.Rows)
{
    if (row[15].ToString() != "New York" || )
    {
        rowsToDelete.Add(row);
    }
}

However, this deletes EVERY row:

foreach (DataRow row in uwDataTable.Rows)
{
    if (row[15].ToString() != "New York" || row[15].ToString() != "Pennsylvania")
    {
        rowsToDelete.Add(row);
    }
}

This seems really simple, but for whatever reason, the "not equal" is picking up too much.

like image 597
Matt Knight Avatar asked Mar 18 '26 14:03

Matt Knight


1 Answers

The reason why

row[15].ToString() != "New York" || row[15].ToString() != "Pennsylvania"

deletes every row is that row[15].ToString() cannot be equal two different strings at the same time, therefore at least one of the two "not equals" is going to evaluate to true, making the overall OR evaluate to true as well.

You are looking for &&, not || in that condition:

row[15].ToString() != "New York" && row[15].ToString() != "Pennsylvania"

This one will be true only when both "not equals" evaluate to true, i.e. the state is not New York and the state is not Pennsylvania.

like image 104
Sergey Kalinichenko Avatar answered Mar 20 '26 03:03

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!