1 Reply Latest reply on Apr 6, 2007 11:05 AM by peterent

    Sort a Collection

      Hello, I am using HTTPService to parse my XML file, and it is stored in xmlData.
      I am storing the values in a ArrayCollection as showed below. Where I am adding an Object inside the ArrayCollection.


      public function getPeopleInEra(era:String):ArrayCollection
      // Temp Collection storage
      var temp:ArrayCollection = new ArrayCollection();

      // Loop through the People
      for(var i:int=0;i<xmlData.length;i++)
      var pd:PersonDetail = xmlData.getItemAt(i) as PersonDetail;

      if(pd.era == era)

      // If no person exists in such ERA then return null
      if(temp.length == 0)
      return null;
      return temp;

      The object PersonDetail has the following public methods, I could set get and set methods but I don't think I need them.

      // Main Information
      public var name:String;
      public var era:String;
      public var born:String;
      public var death:String;
      public var description:String;
      public var image:String;

      Now I wish to sort my above collection by name So my getPeopleInEra method will return a sorted ArrayCollection sorted by name. How can I do that thing, in other languages I could use IComparable or some sort of interface.

      I have looked into Sort ( http://livedocs.adobe.com/flex/2/langref/mx/collections/Sort.html )
      But it seems they are just sorting an array, so how would I go around doing this :)

      Thanks in Advance!
        • 1. Re: Sort a Collection
          peterent Level 2
          You need to use the Sort and SortField classes. You first create a Sort object, giving it the SortFields (which name the fields in your object that are to be sorted, and the direction - ascending, descending).

          Then you assign the Sort object to the ArrayCollection's sort property. After you do that, call the ArrayCollection's refresh() function to start sorting. From then on, until you remove the sort, each operation on the ArrayCollection (eg, addItem) will automatically sort.