Confronto di DataRows (LINQ to DataSet)

LINQ (Language Integrated Query) definisce diversi operatori sui set per confrontare gli elementi di origine e verificarne l'uguaglianza. LINQ fornisce gli operatori sui set seguenti:

Questi operatori confrontano gli elementi di origine chiamando i metodi GetHashCode e Equals su ogni raccolta di elementi. Nel caso di un oggetto DataRow, questi operatori eseguono un confronto di riferimento, che tuttavia non corrisponde in genere al comportamento ideale per le operazioni sui set eseguite su dati tabulari. Per le operazioni sui set si desidera in genere stabilire se i valori degli elementi, e non i riferimenti agli elementi, sono uguali. È stata quindi aggiunta la classe DataRowComparer a LINQ to DataSet. Questa classe può essere usata per confrontare i valori di riga.

La classe DataRowComparer contiene un'implementazione del confronto di valori per DataRow, pertanto può essere usata per operazioni sui set, ad esempio Distinct. Non è possibile creare direttamente un'istanza di questa classe ed è invece necessario usare la proprietà Default per restituire un'istanza di DataRowComparer<TRow>. Viene quindi chiamato il metodo Equals e i due oggetti DataRow da confrontare vengono passati come parametri di input. Il metodo Equals restituisce true se il set ordinato di valori di colonna è uguale in entrambi gli oggetti DataRow; in caso contrario, false.

Esempio

In questo esempio viene usato Intersect per restituire i contatti presenti in entrambe le tabelle.

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable contactTable = ds.Tables["Contact"];

// Create two tables.
IEnumerable<DataRow> query1 = from contact in contactTable.AsEnumerable()
                              where contact.Field<string>("Title") == "Ms."
                              select contact;

IEnumerable<DataRow> query2 = from contact in contactTable.AsEnumerable()
                              where contact.Field<string>("FirstName") == "Sandra"
                              select contact;

DataTable contacts1 = query1.CopyToDataTable();
DataTable contacts2 = query2.CopyToDataTable();

// Find the intersection of the two tables.
var contacts = contacts1.AsEnumerable().Intersect(contacts2.AsEnumerable(),
                                                    DataRowComparer.Default);

Console.WriteLine("Intersection of contacts tables");
foreach (DataRow row in contacts)
{
    Console.WriteLine("Id: {0} {1} {2} {3}",
        row["ContactID"], row["Title"], row["FirstName"], row["LastName"]);
}
' Fill the DataSet.
Dim ds As New DataSet()
ds.Locale = CultureInfo.InvariantCulture
' See the FillDataSet method in the Loading Data Into a DataSet topic.
FillDataSet(ds)

Dim contactTable As DataTable = ds.Tables("Contact")

Dim query1 = _
    From contact In contactTable.AsEnumerable() _
    Where contact.Field(Of String)("Title") = "Ms." _
    Select contact

Dim query2 = _
    From contact In contactTable.AsEnumerable() _
    Where contact.Field(Of String)("FirstName") = "Sandra" _
    Select contact

Dim contacts1 = query1.CopyToDataTable()
Dim contacts2 = query2.CopyToDataTable()

Dim contacts = contacts1.AsEnumerable() _
    .Intersect(contacts2.AsEnumerable(), DataRowComparer.Default)

Console.WriteLine("Intersect of employees tables")

For Each row In contacts
    Console.WriteLine("Id: {0} {1} {2} {3}", _
            row("ContactID"), row("Title"), row("FirstName"), row("LastName"))
Next

Esempio

Nell'esempio seguente vengono confrontate due righe e ne vengono ottenuti i codici hash.

' Fill the DataSet.
Dim ds As New DataSet()
ds.Locale = CultureInfo.InvariantCulture
' See the FillDataSet method in the Loading Data Into a DataSet topic.
FillDataSet(ds)

' Get two rows from the SalesOrderHeader table.
Dim table As DataTable = ds.Tables("SalesOrderHeader")
Dim left = table.Rows(0)
Dim right = table.Rows(1)

' Compare the two different rows.
Dim comparer As IEqualityComparer(Of DataRow) = DataRowComparer.Default
Dim bEqual = comparer.Equals(left, right)

If (bEqual = True) Then
    Console.WriteLine("Two rows are equal")
Else
    Console.WriteLine("Two rows are not equal")
End If

' Output the hash codes of the two rows.
Console.WriteLine("The hashcodes for the two rows are {0}, {1}", _
    comparer.GetHashCode(left), _
    comparer.GetHashCode(right))

Vedi anche