【问题标题】:Sort ArrayList including custom struct对包含自定义结构的 ArrayList 进行排序
【发布时间】:2011-06-25 14:48:44
【问题描述】:

我写了一个结构

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

在我的程序中,我会将这些结构添加到 ArrayList。我怎样才能对它们进行排序?我尝试了 IComparer,但不幸的是我无法理解它是如何工作的。

【问题讨论】:

  • 小心可变结构。

标签: c# sorting struct arraylist icomparer


【解决方案1】:

我没有对此进行测试,但它类似于......

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

【讨论】:

    【解决方案2】:
    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);
        });
    }
    

    【讨论】:

      【解决方案3】:

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

      基本思路是

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

      Another (a bit long-drawn) example 说明了这一点

      【讨论】:

        猜你喜欢
        • 2019-08-08
        • 2012-05-10
        • 2010-10-22
        • 2010-12-21
        • 1970-01-01
        • 1970-01-01
        • 2011-02-16
        相关资源
        最近更新 更多