Zacznijmy od tego że nie wiem z jakiej książki/tutoriala się uczysz, ale wywal ją/go. ArrayList jest przestarzała już od bardzo dawna. Ale ok, nieważne.
Najpierw szkielet implementacji:
class Element
{
public Element(string nazwa, int rok, float zawartosc)
{
this.Nazwa = nazwa;
this.RokZalozania = rok;
if (zawartosc < 0 || zawartosc > 1)
{throw new ArgumentException("Zawartość ma zawierać się od 0 (0%) do 1 (100%)");}
this.ZawartoscChmielu = zawartosc;
}
public string Nazwa { get; set; }
public int RokZalozania { get; set; }
// ...
public float ZawartoscChmielu { get; set; }
}
class Program
{
static void Display(Element[] elements)
{
int ndx = 0;
foreach (var el in elements)
{
Console.WriteLine(ndx.ToString() + ": " +
el.Nazwa + " " +
el.RokZalozania + " " +
el.ZawartoscChmielu);
ndx++;
}
}
static void Main(string[] args)
{
ArrayList al = new ArrayList();
al.Add(new Element("asdf", 1999, 0.05f));
al.Add(new Element("foo", 1992, 0.03f));
al.Add(new Element("asdf", 1845, 0.07f));
Element[] els = (Element[])al.ToArray(typeof(Element));
Display(els);
Console.ReadKey(true);
}
}
I teraz sposoby żeby to posortować:
I. za pomocą IComparable -
zmieniamy klasę element w taki sposób:
class Element : IComparable // !!!
{
// to samo...
public int CompareTo(object obj)
{
return this.ZawartoscChmielu.CompareTo(((Element)obj).ZawartoscChmielu);
}
}
i dodajemy
al.Sort();
w miejscu gdzie lista ma być sortowana (najlepiej tuż po stworzeniu).
II: IComparer:
class ElementByChmielComparer : IComparer // Z nazwy wyszło spagetti bo wymieszałem polski z angielskim. nvm.
{
public int Compare(object x, object y)
{
return ((Element)x).ZawartoscChmielu.CompareTo(((Element)y).ZawartoscChmielu);
}
}
i dodajemy
al.Sort(new ElementByChmielComparer());
po stworzeniu listy.
// -----
Gdybyś zamiast prehistorycznej ArrayListy używał List<Element> To wystarczyłoby wywołać (bez żadnych modyfikacji niczego):
al.Sort((x, y) => x.ZawartoscChmielu.CompareTo(y.ZawartoscChmielu));