ArrayList sorting on stronged typed objects

J

JDeats

If I have

class Student
{
public string LastName
public string FirstName
public int Age;
public int ID;
}

and I have an ArrayList that's storing only Student objects, how can I
sort the ArrayList by LastName? Using a IComparer class appears to only
allow < > comparisons on a numeric field...
 
C

Cor Ligthert [MVP]

JDeats,

You investigated already the power of the DataTable Class, it is completely
build in, so very cheap to use and can used to be inherited and than
completely strongly typed.

Cor
 
J

Jon Skeet [C# MVP]

JDeats said:
If I have

class Student
{
public string LastName
public string FirstName
public int Age;
public int ID;
}

and I have an ArrayList that's storing only Student objects, how can I
sort the ArrayList by LastName? Using a IComparer class appears to only
allow < > comparisons on a numeric field...

No, IComparer is the way to go here - just return the value of
x.LastName.CompareTo(y.LastName);
 
O

Otis Mukinfus

G

Guest

Actually, CompareTo() is defined in IComparable. IComparer defines Compare().
--
Dale Preston
MCAD C#
MCSE, MCDBA
 
J

Jon Skeet [C# MVP]

Dale said:
Actually, CompareTo() is defined in IComparable. IComparer defines
Compare().

Indeed - but I was suggesting calling String.CompareTo when
implementing Compare.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top