Sorting an ArrayList

  • Thread starter Thread starter Nick
  • Start date Start date
N

Nick

Hi !

I have Objects in my ArrayList
These Objects contain a String called "Name".
And i want that ArrayList to sort
it's objects using the Name element of each
object and not something else of the object ?!?
I think this is somehow accomplished using the
Comparer class, but i have not checked it out yet.

Please help !

Thanks, nick
 
Nick said:
I have Objects in my ArrayList
These Objects contain a String called "Name".
And i want that ArrayList to sort
it's objects using the Name element of each
object and not something else of the object ?!?
I think this is somehow accomplished using the
Comparer class, but i have not checked it out yet.

Use ArrayList.Sort(IComparer) where you write an implementation of
IComparer which compares two of your objects by name. Alternatively,
make your objects themselves implement IComparable in a similar way,
and just call ArrayList.Sort.
 
Hi !

I have Objects in my ArrayList
These Objects contain a String called "Name".
And i want that ArrayList to sort

Instead of an ArrayList, use a SortedList. You can place the Name in the
key and it will be sorted by name.
 
I have Objects in my ArrayList
These Objects contain a String called "Name".
And i want that ArrayList to sort
it's objects using the Name element of each
object and not something else of the object ?!?

Here's how I did it (I also have a pretty good typesafe ArrayList for
this class courtesy of (e-mail address removed), if you'd like to see it):

public class QRow : IComparable, ICloneable
{
public int qId;
public int testId;
public string objective;
public int placement;

////////////////////////////////////////////////////////////
public QRow()
{
qId = 0;
testId = 0;
objective = "";
placement = -1;
}

////////////////////////////////////////////////////////////
public QRow(QRow other)
{
this.qId = other.qId;
this.testId = other.testId;
this.objective = other.objective;
this.placement = other.placement;
}

#region IComparable Members

public int CompareTo(object rhs)
{
QRow r = (QRow) rhs;
return this.placement.CompareTo(r.placement);
}

#endregion

#region ICloneable Members

public object Clone()
{
return new QRow(this);
}

#endregion
}
 
Back
Top