DataRow 비교(LINQ to DataSet)

LINQ(Language-Integrated Query)에는 소스 요소가 같은지 여부를 확인하는 다양한 집합 연산자가 정의되어 있습니다. LINQ에서는 다음과 같은 집합 연산자를 제공합니다.

이러한 연산자는 각 요소 컬렉션에 대해 GetHashCodeEquals 메서드를 호출하여 소스 요소를 비교합니다. DataRow의 경우 이러한 연산자는 참조 비교를 수행합니다. 참조 비교는 일반적으로 표 형식의 데이터에 대한 집합 연산에는 적합하지 않습니다. 집합 연산에서는 일반적으로 요소 값이 같은지 여부와 요소 값이 요소 참조가 아닌지 여부를 확인합니다. 따라서 DataRowComparer 클래스가 LINQ to DataSet에 추가되었습니다. 이 클래스는 행 값을 비교하는 데 사용할 수 있습니다.

DataRowComparer 클래스에는 DataRow에 대한 값 비교 구현이 있으므로 이 클래스는 Distinct와 같은 집합 연산에 사용할 수 있습니다. 이 클래스는 직접 인스턴스화할 수 없기 때문에 Default 속성을 사용하여 DataRowComparer<TRow>의 인스턴스를 반환해야 합니다. 그런 다음 Equals 메서드를 호출하면서 비교할 두 DataRow 개체를 입력 매개 변수로 전달합니다. Equals 메서드에서는 두 true 개체에 있는 정렬된 열 값 집합이 같으면 DataRow를 반환하고, 그렇지 않으면 false를 반환합니다.

예시

이 예제에서는 Intersect를 사용하여 두 테이블에 있는 연락처를 반환합니다.

// 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

예시

다음 예제에서는 두 행을 비교한 다음 두 행의 해시 코드를 가져옵니다.

' 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))

참고 항목