DataRow comparison not working properly

I am trying to compare two DataRowin a loop. However, the following statement ifdoes not return true:

if (dt1.Rows[0]["Name"] == dt2.Rows[b]["Name"]) {
    // This never executes
}

However, if I add .ToString()at the end of each DataRow, the operator ifwill return true:

if (dt1.Rows[0]["Name"].ToString() == dt2.Rows[b]["Name"].ToString()) {
    // This now executes
}

The "Name" column refers to the same table / column. So the question is pretty simple ... What am I doing wrong?

Thanks
Steven

+3
source share
3 answers

As itsmatt said , your first snippet performs a comparative comparison. An alternative to calling ToStringis to use Object.Equals:

if (Object.Equals(dt1.Rows[0]["Name"], dt2.Rows[b]["Name"])) {
    // stuff
}

, .

+7

, , , . " ?", , , , "". ToString(), . .

MS == .

+9

==, , ReferenceEquals() - , object .

ToString() string, ==, .

+4
source

Source: https://habr.com/ru/post/1704269/


All Articles