简体   繁体   中英

How can I be sure that List.Contains works for a list of DataTables?

If I have this:

 List<DataTable> listDataTables = functionToAddSomeDataTables();

and I want to do a comparison like this:

if(listDataTables.Contains(aDataTable))
{
   //do something.
}

How can I know if it is comparing the reference or the schema or the content or all of the above?

Do I need to write my own IEquatable.Equals to make sure it works properly or can I trust that the built in .Equals for DataTable works as I would hope?

Is there a general rule or observation for knowing when .Contains, or similar comparisons are by reference or by value?

Thanks in advance :)

You have to write your own Equals method and compare the needed properties where. The built in (default) Contains() method will check values for value types (string, int...) and references for reference types (your class is a reference type)

List<T>.Contains uses the object's object.Equals(object) method. Since DataTable 's documentation says that its Equals was inherited from Object.Equals , the default Object.Equals implementation of reference comparison is what will be used. If you want the comparison by something else, include that equality comparer by using LINQ's Contains method.

(as an example, compare DataTable Methods and Decimal Methods : only Decimal lists Equals on the list on the left, and says "(Overrides ValueType.Equals(Object).)" instead of "(Inherited from Object.)")

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