Sort a list of customized objects in CSharp
Description
The following code shows how to sort a list of customized objects.
Example
/*from w w w . ja v a 2 s .c om*/
using System;
using System.Collections;
class Album : IComparable, ICloneable {
private string _Title;
private string _Artist;
public Album(string artist, string title) {
_Artist = artist;
_Title = title;
}
public string Title {
get {
return _Title;
}
set {
_Title = value;
}
}
public string Artist {
get {
return _Artist;
}
set {
_Artist = value;
}
}
public override string ToString() {
return _Artist + ",\t" + _Title;
}
public int CompareTo(object o) {
Album other = o as Album;
if (other == null)
throw new ArgumentException();
if (_Artist != other._Artist)
return _Artist.CompareTo(other._Artist);
else
return _Title.CompareTo(other._Title);
}
public object Clone() {
return new Album(_Artist, _Title);
}
}
class MainClass {
static void Main(string[] args) {
ArrayList arr = new ArrayList();
arr.Add(new Album("G", "A"));
arr.Add(new Album("B", "G"));
arr.Add(new Album("S", "A"));
arr.Sort();
foreach (Album a in arr) {
Console.WriteLine(a);
}
}
}
The code above generates the following result.