排序包含自定义结构的ArrayList

本文关键字:ArrayList 结构 自定义 包含 排序 | 更新日期: 2023-09-27 18:00:16

我写了一个结构

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

在我的程序中,我会将这些结构添加到ArrayList中。我该如何分类?我试过IComparer,但不幸的是,我无法理解它是如何工作的。

排序包含自定义结构的ArrayList

我没有测试它,但它有点像。。。

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;
    }
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);
    });
}

查看此链接中的示例http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx

基本思想是

  • 创建一个IComparer实现,该实现根据自定义比较条件返回-1(小于)、0(等于)或1(大于)
  • 接下来,将此类的一个实例传递给List()的Sort方法

另一个(画得有点长)例子说明了这个