Testing equality of DataColumn values in C#
I've written some code to test equality between column values in DataTables when the column type isn't known.
Testing directly like this:
row["Foo"] == row["Bar"]
always results in false, presumably because object's implementation of Equals uses ReferenceEquals.
So I've resorted to:
row["Foo"].ToString() == row["Bar"].ToString()
This works (at least for the cases I've encountered so far), but it seems a little, well, manky.
Can anyone think of a reason I shouldn't do it this way, or suggest a better wa开发者_开发知识库y? Remember I don't know the column types at design time, so casting is not an option.
Thanks
David
Try row["Foo"].Equals(row["bar"])
.
When you compare objects using == and there is no predefined or user-defined == operator, C# will compare them using reference equality. If you want to call the Equals method, you need to write it out as a method call.
row["Foo"].Equals(row["Bar"])
?
why not use Equals if they are string.
row["foo"].ToString().Equals(row["Bar"].ToString());
精彩评论