我寫了一個struct排序ArrayList中包括自定義結構
public struct SeasonEpisodeNr { public int seasonNr; public int episodeNr; }
在我的計劃,我將這些結構添加到一個ArrayList。我如何分類?我試過IComparer,但不幸的是我無法理解它是如何工作的。
我寫了一個struct排序ArrayList中包括自定義結構
public struct SeasonEpisodeNr { public int seasonNr; public int episodeNr; }
在我的計劃,我將這些結構添加到一個ArrayList。我如何分類?我試過IComparer,但不幸的是我無法理解它是如何工作的。
我沒有測試此的排序方法,但它是像...
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;
}
工程就像魅力!謝謝! – theknut
退房的例子在這個環節 http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx
的基本思路是
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);
});
}
小心可變結構。 – Marc
什麼是可變結構? – theknut