Comparing DataRows (LINQ to DataSet)

 

Language-Integrated Query (LINQ) defines various set operators to compare source elements to see if they are equal. LINQ provides the following set operators:

These operators compare source elements by calling the GetHashCode and Equals methods on each collection of elements. In the case of a DataRow, these operators perform a reference comparison, which is generally not the ideal behavior for set operations over tabular data. For set operations, you usually want to determine whether the element values are equal and not the element references. Therefore, the DataRowComparer class has been added to LINQ to DataSet. This class can be used to compare row values.

The DataRowComparer class contains a value comparison implementation for DataRow, so this class can be used for set operations such as Distinct. This class cannot be directly instantiated; instead, the Default property must be used to return an instance of the DataRowComparer. The M:System.Data.DataRowComparer.Equals(System.Data.DataRow,System.Data.DataRow) method is then called and the two DataRow objects to be compared are passed in as input parameters. The M:System.Data.DataRowComparer.Equals(System.Data.DataRow,System.Data.DataRow) method returns true if the ordered set of column values in both DataRow objects are equal; otherwise, false.

This example uses Intersect to return contacts that appear in both tables.

[!CODE [DP LINQ to DataSet Examples#Intersect2](../CodeSnippet/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples#intersect2)]

Example

The following example compares two rows and gets their hash codes.

[!CODE [DP LINQ to DataSet Examples#CompareDifferentRows](../CodeSnippet/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples#comparedifferentrows)]

DataRowComparer
Loading Data Into a DataSet
LINQ to DataSet Examples

Show: