September 23, 2007

Using The IComparer and IComparable Interfaces

Sorting and the IComparer and IComparable Interfaces
private class XXXComparer : IComparer
{
    public XXXComparer()
    {
    }

    #region IComparer Members

    public int Compare(IXXX x, IXXX y)
    {
        return x.SomeProperty.CompareTo(y.SomeProperty);
    }

    #endregion
}

Say you have a list of IXXX, you can sort it with this
m_XXX_List.Sort(new XXXComparer());

private class SomeObjectComparer : IComparer
{
 #region IComparer Members

 public int Compare(object x, object y)
 {
  IXXX xi = x as IXXX;
  IXXX yi = y as IXXX;

         return xi.SomeProperty.CompareTo(yi.SomeProperty);
 }

 #endregion
}


private class XXX : IComparable
{
    #region IComparable Members

    public int CompareTo(XXX other)
    {
        return this.SomeProperty.CompareTo(other.SomeProperty);
    }

    #endregion
}

Say you have a list of XXX, you can sort it with this
m_XXX_List.Sort();

// Simplest Enumerator. Can enumerate the objects without 
// exposing the underlying list
public IEnumerable Processes()
{
    foreach (IProcess process in m_Processes)
    {
       yield return process;
    }
}

No comments: