Hansanho
Hansanho

Reputation: 293

IComparer.CompareTo(Object a, Object b)

I have an Arraylist with 10 or more Level object. These objects all have a Level ID. I try now to write an IComparer.CompareTo(Level a,Level b). I don't really know how to Implement this. Never worked with IComparer and when I read the MSDN Libary I don't get smarter.

I tried this:

  public int CompareTo(Level a, Level b)
    {
        if (a.LevelID < b.LevelID)
        {
            return -1;
        }
        else if (a.LevelID == b.LevelID)
        {
            return 0;
        }
        else
            return 1;
    }
this._alLevel.Sort(CompareTo(Level[0],Level[1])

_alLevel is my Arraylist with my Level object.

I am a beginner...

Upvotes: 0

Views: 1092

Answers (2)

dbc
dbc

Reputation: 117026

I strongly recommend you store your levels in a generic List<Level>. It guarantees type-safety in your code and improves performance by removing the need to do run-time casting of objects into the expected type.

But, if you are determined to use a non-generic ArrayList, you must create a comparer that implements the non-generic IComparer interface, like so:

public class LevelComparer : IComparer<Level>, IComparer
{
    #region IComparer<Level> Members

    public int Compare(Level x, Level y)
    {
        if (object.ReferenceEquals(x, y))
            return 0;
        if (x == null)
            return 1;
        else if (y == null)
            return -1;
        return x.LevelID.CompareTo(y.LevelID);
    }

    #endregion

    #region IComparer Members

    public int Compare(object x, object y)
    {
        return Compare(x as Level, y as Level);
    }

    #endregion
}

(Note that my comparer also implements the generic IComparer<Level> interface so you could use it with a List<Level>. Also, the null checks are there in case the objects cannot be cast to Levels. In a purely generic comparer I probably wouldn't bother.)

Next, pass an instance of the comparer to the sort method of your arraylist:

arrayList.Sort(new LevelComparer());

Upvotes: 2

Lorenzo Dematt&#233;
Lorenzo Dematt&#233;

Reputation: 7849

I imagine your _alLevel is a List<Level>

Then, you need to implement IComparer<Level>, like

 public class LevelComparator: IComparer<Level> {
  public int CompareTo(Level a, Level b)
  {
    if (a.LevelID < b.LevelID)
    {
        return -1;
    }
    else if (a.LevelID == b.LevelID)
    {
        return 0;
    }
    else
        return 1;
  }
}

Then, you can instantiate the comparator and pass it to Sort:

  this._alLevel.Sort(new LevelComparator());

Inside, the Sort method will use you CompareTo method to perform the sorting

Upvotes: 1

Related Questions