0

I wrote a struct

public struct SeasonEpisodeNr { public int seasonNr; public int episodeNr; }

During my program I will add those structs to an ArrayList. How can I sort them? I tried the IComparer but unfortunately I was not able to understand how it works.

Gishu
  • 134,492
  • 47
  • 225
  • 308
theknut
  • 2,533
  • 5
  • 26
  • 41

3 Answers3

0

Check out the example in this link http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx

The basic idea is to

  • Create a IComparer implementation that returns -1 (less than), 0 (equals) or 1 (greater than) based on your custom comparison criteria.
  • Next pass an instance of this class to the Sort method of your List()

Another (a bit long-drawn) example that illustrates this

Gishu
  • 134,492
  • 47
  • 225
  • 308
0

I didn't test this but it's something like...

public struct SeasonEpisodeNr: IComparable
{ 
    public int seasonNr; 
    public int episodeNr;
    public int CompareTo(Object Item)
    {
        SeasonEpisodeNr that = (SeasonEpisodeNr) Item;

        if (this.seasonNr > that.seasonNr)
            return -1;
         if (this.seasonNr < that.seasonNr)
            return 1;

         if (this.episodeNr > that.episodeNr)
             return -1;
         if (this.episodeNr < that.episodeNr)
             return 1;

         return 0;
    }
Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
0
public struct SeasonEpisodeNr
{
    public SeasonEpisodeNr(int seasonNr, int episodeNr)
    {
        this.seasonNr = seasonNr;
        this.episodeNr = episodeNr;
    }

    public int seasonNr; public int episodeNr; 
}

static void Main(string[] args)
{
    List<SeasonEpisodeNr> list = new List<SeasonEpisodeNr>();
    list.Add(new SeasonEpisodeNr(1, 2));
    list.Add(new SeasonEpisodeNr(1, 1));
    list.Sort((a, b) =>
    {
        //implement comparison, e.g. compare season first and if equal compare the epizods
        int res = a.seasonNr.CompareTo(b.seasonNr);
        return res != 0 ? res : a.episodeNr.CompareTo(b.episodeNr);
    });
}
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95