排序ArrayList包括自定义结构

时间:2011-06-25 14:48:44

标签: c# sorting struct arraylist icomparer

我写了一个结构

  

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

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

3 个答案:

答案 0 :(得分:0)

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

基本想法是

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

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

答案 1 :(得分:0)

我没有对此进行测试,但它就像......

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 :(得分: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);
    });
}