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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With