Sorting an ArrayList.

Discussion in 'ASP .Net' started by Jose, Aug 1, 2005.

  1. Jose

    Jose Guest

    Dear All,

    I have been staring at this for ages now and I still can't see why it
    doesn't work. Any help will be GREATLY appreciated.

    I am simply trying to sort an arraylist using my own instance of
    IComparer. Code below...

    Quite simply it doesn't work. Can anyone see where I'm going wrong?

    Thanks in advance,
    Jose

    <code>
    public class TabDetail
    {
    public int ID;
    public string Name;
    public int Order;
    public string URL;
    }

    public class TabOrderComparer: IComparer
    {
    public int Compare(object o1, object o2)
    {
    int SortID1 = ((TabDetail)o1).SortID;
    int SortID2 = ((TabDetail)o2).SortID;

    return SortID1.CompareTo(SortID2);
    }
    }
    public class TabSettings
    {
    public ArrayList Tabs;
    public int ActiveTab;

    public TabSettings()
    {
    this.Tabs = new ArrayList();

    PopulateTabs();

    this.Tabs.Sort(new TabOrderComparer());
    }

    private void PopulateTabs()
    {
    Classes.DataAccessor oDA = new Classes.DataAccessor();
    DataTable dtTabs = oDA.ReadTabs();

    foreach(DataRow drTab in dtTabs.Rows)
    {
    TabDetail oTab = new TabDetail();

    oTab.ID = (int)drTab["ID"];
    ...
    //Populate the rest of the properties here...
    }
    }
    }
    </code>
     
    Jose, Aug 1, 2005
    #1
    1. Advertisements

  2. Jose

    Karl Seguin Guest

    Works for me. I had to modify your code a bit to (a) have a SortID and (b)
    populate it from a source other than your database, I ended up with:

    private void PopulateTabs()
    {
    for (int i = 0; i < 100; ++i)
    {
    TabDetail oTab = new TabDetail();
    oTab.ID = rand.Next();
    oTab.SortID = oTab.ID;
    Tabs.Add(oTab);
    }
    }

    where rand was just a random number generator:
    public class TabSettings
    {
    private Random rand = new Random();


    Karl
     
    Karl Seguin, Aug 1, 2005
    #2
    1. Advertisements

  3. Jose

    Jose Guest

    Thanks for your reply Karl.

    Sorry about the code, I just copied a selection and obviously missed
    one or two important things!! :)

    I'll have another look....

    Jose
     
    Jose, Aug 2, 2005
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.