03Usr
03Usr

Reputation: 3435

Compare two datatables while taking sorting into account

I have two data tables as below and I am using the below to compare the two:

var diffResult = actual.AsEnumerable().Except(expected.AsEnumerable(), 
DataRowComparer.Default);

Assert.IsFalse(diffResult.Any());

In this scenario diffResult does not return anything, and works fine when I want to make sure the two tables match. However this way of comparing does not take the sorting into account.

How can I compare the two tables and return True if the two tables contain the same data and they are both ordered the same way?

actual
-------------------------
 Code  |   Name 
--------------------------
 101  |  A
 101  |  B
 101  |  C
--------------------------

expected
-------------------------
 Code|   Name 
--------------------------
 101  |  C
 101  |  B
 101  |  A
--------------------------

Upvotes: 0

Views: 253

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109185

Use SequenceEqual.

bool seqEqual = actual.AsEnumerable()
               .SequenceEqual(expected.AsEnumerable(), DataRowComparer.Default);

SequenceEqual is only true when both lists have the same number of elements in exact the same order as defined by the comparer.

Upvotes: 2

Related Questions