简体   繁体   中英

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 way? 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"])吗?

如果它们是字符串,为什么不使用等于。

row["foo"].ToString().Equals(row["Bar"].ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM