Search code examples
c#sortingexceptionicomparer

How to overcome the ArgumentException while sorting using the IComparer interface in C#?


I'm sorting an array of RowRanges using the IComparer. It works fine when the row range is upto 16. Beyond 16, the exception occurs stating that, sorting is not performed and the exception is thrown stating that Soting cannot be performed, because the values compared to itself and a value is compared repeatedly to other. While debugging , I found that the issue occurs during objects taken for for comparison. But how is that exception occurs after 16, while it is working fine upto 16? Please refer to the below code snippet.

internal class ColComparer : IComparer
{

    public int Compare(object a, object b)
    {
        if (a == null || b == null)
        {
            return System.Collections.Comparer.Default.Compare(a, b);
        }

    GridRangeInfo r0 = (GridRangeInfo)a;
    GridRangeInfo r1 = (GridRangeInfo)b;

    if (r0 == r1)
    {
        return 0;
    }
    else
    {
        if (r0.RangeType == GridRangeInfoType.Table)
        {
            return -1;
        }
        else if (r1.RangeType == GridRangeInfoType.Table)
        {
            return 1;
        }
        else if (r0.RangeType == GridRangeInfoType.Rows)
        {
            return -1;
        }
        else if (r1.RangeType == GridRangeInfoType.Rows)
        {
            return 1;
        }
        else if (r0.Left != r1.Left)
        {
            return r0.Left - r1.Left;
        }
        else if (r0.Right != r1.Right)
        {
            return r0.Right - r1.Right;
        }
        else if (r0.Top != r1.Top)
        {
            return r0.Top - r1.Top;
        }
        else
        {
            return r0.Bottom - r1.Bottom;
        }
    }
}
}


class SortArray 
{
    //Array Data
    //

    GridRangeInfo[] ranges = new GridRangeInfo[this.Count];                 
    Array.Sort(ranges, new GridRangeInfo.ColComparer());
 }

Let me know where the exception occurs and share your ideas to resolve this.

Thanks in Advance,

Sindhu


Solution

  • The conditions such as r0.RangeType == GridRangeInfoType.Table .. return -1 produce a non-stable result. This is because it depends on "which" item is r0 and r1.

    Follow the same if-then-return pattern as with the rest of the function - where r0.X is compared to r1.X and then 'something is done based on that'.

    eg.

        if (r0.RangeType != r1.RangeType) {
        {
            if (r0.RangeType == GridRangeInfoType.Table) {
               return -1; // r0 first - prioritize 'Table' range types
            } else {
               return 1; // r1 first
            }
        }