I’m trying to compare two DataRows in a loop. However, the following if statement doesn’t return true:
if (dt1.Rows[0]['Name'] == dt2.Rows[b]['Name']) { // This never executes }
However, if I add .ToString() to the end of each DataRow, the if statement returns true:
if (dt1.Rows[0]['Name'].ToString() == dt2.Rows[b]['Name'].ToString()) { // This now executes }
The column ‘Name’ is from the same table/column. So the question is quite simple… What am I doing wrong?
Thanks
Stephen
As itsmatt has said, your first snippet is doing a reference comparison. An alternative to calling
ToStringis to useObject.Equals:The reason for using the static method instead of the instance method is to avoid problems with null references.