This short article describes a simple extension method for comparing sequences of values, and therefore sorting sequences against each other.
The original need for these extension methods was that we were displaying a series of lists in grid cells, and we wanted to be able to sort the grid by that column. Ordinary alphabetical sorting on the display text was inadequate because if some elements were numbers, then alphabetical falls short of being useful. Using natural sorting on the display text was an option, but this was a simpler route.
What about Enumerable.SequenceEqual()?
While this code does resemble
SequenceEqual, it's intended use is quite different. Since this provides comparison and not just equality, it enables you to sort sequences of sequences, rather than just testing if two sequencces are the same or not.
Using the Code
To use the code, simply include:
Or copy the code to your own project and modify the namespace.
After this, you can:
SequenceCompare<T> on any
List<IEnumerable<T>>.Sort() passing in
- Also specify your own
IComparer<T> instance to do the element comparisons
var random = new Random();
var values = new List<IEnumerable<int>>();
for (int i = 0; i < 10; ++i)
var items = new List<int>();
var count = random.Next(0, 6);
for (int j = 0; j < count; ++j)
This will produce something like this:
1 1 2 2 3
- 21st May, 2009: Initial post