Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sorting arraylist of structures

Status
Not open for further replies.

dudleys

Technical User
Apr 28, 2005
31
AU
Hi,

I have an ArrayList of structures and I want to sort the array on different members of the structure so that I can give a rank each element of the array.

So I thought I would sort it for each member in turn add add a rank member to the structure for each member i want to sort

Confusing I bet.

How else would you do this? I want to step through a database fill an array then sort by differen members and then rank each member in the array so that I can create a table with the member values and there rank next to it

Thanks for any help given
dudley
 
using sorted arraylist we can store rank and value and sort them by rank. Refer the following code
Dim slsStates As New SortedList

slsStates.Add("CA", "California")
slsStates.Add("AZ", "Arizona")
slsStates.Add("NV", "Nevada")

' slsStates order:
'
' Keys | Values
' ---------------
' AZ | Arizona
' CA | California
' NV | Nevada
 
I think you may need to use sweths' approache above.
Write a class the put each member of your structure into it's own sortedList. Since your structure members are custom I don't think there is going to anything off the shelf that will do it without some extra writing.
 
It seems there is no other way then to put each in its own sorted list.

Ok thanks
 
If you add an implementation of IComparer to your data structure (hopefully it's a class, not a struct). You can then call the .Sort method on the ArrayList.
Code:
Class States : IComparer
{
   public string StateAbbr;
   public string StateFull;

   // Default constructor
   public States()
   {
   }

   public States(string abbr, string full)
   {
      StateAbbr = abbr;
      StateFull = full;
   }

   // Implementation of IComparer
   // sorts by the state abbreviation
   public int Compare(object x, object y)
   {
      if (x == null)
         return -1;
      else
         States stateX = x as States;

      if (y == null)
         return 1;
      else
         States stateY = y as States;
      
      return stateX.StateAbbr.CompareTo(stateY.StateAbbr);
   }
}
to use it:
Code:
ArrayList a = new ArrayList();
a.Add(new States("CA", "California"));
a.Add(new States("AZ", "Arizona"));
a.Add(new States("NV", "Nevada"));

a.Sort();
Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top