Lingering Problems
I found one of the problems with sorting; I didn't calculate desending sorting. For instance, the integer values -1, 0, 1 tell you whether the first value is less than the second value, the same, or opposite. However, in descending order, you have to reverse the direction. So, in order to do that, you have to do this:
public override int Compare(MetadataAttribute x, MetadataAttribute y)
{
int value = x.Name.CompareTo(y.Name);
if (this.Ascending)
return value;
else
return 1 - value;
}
This produced some weird results; the descending sort didn't sort correctly. I thought that it would have, but it didn't. But after thinking about it, this doesn't seem right. After all, if the value is a 1, this would produce a 0, which is incorrect (should be -1). So, I corrected this, and it worked.
public override int Compare(MetadataAttribute x, MetadataAttribute y)
{
int value = x.Name.CompareTo(y.Name);
if (this.Ascending)
return value;
else
return 0 - value;
}
If 1, 0-1 equals -1, which reverses it. Rather than forcing each compare method to do this, I refactored by creating a base method in the collection, called DetermineSortingDirection. You pass it the normal integer result, and it makes that determination:
protected int DetermineSortingValue(int comparisonValue)
{
if (this.Ascending)
return comparisonValue;
else
return 0 - comparisonValue;
}
And, in my compare methods (base or derived), this is the new version:
public override int Compare(MetadataAttribute x, MetadataAttribute y)
{
int value = x.Name.CompareTo(y.Name);
return base.DetermineSortingValue(value);
}
And it worked. So, in realizing that the problem is with the base class, I wonder if that is my insertrange problem. Looking back at the collection method, I have:
public void InsertRange(int index, T[] items)
{
for (int i = items.Length; i >= 0; i--)
{
this.List.Insert(index, items[i]);
}
}
However, I notice that I could have an off-by-one error. Shouldn't it be items.Length-1? I add that in, and run the tests again. One failure, the original simplistic collection sort. And after looking at it, it makes sense why. Because I'm using the generic collection method, and not overriding the Compare method, it uses ToString, which doesn't really compare the values at all. So I will remove this method from the test, and that gives me the attached result: all green.