none
How to sort an ArrayLIst that contains objects of data types

    Question

  • I have the following code that perform the default ArrayList sort but would like to know how to sort the arraylist by the attributes of the data object such as the empID, fName, etc....

    using System;
    using System.Linq;
    using System.Text;
    using System.Collections;
    using System.Collections.Generic;


    public class Employee : IComparable
    {
        /* These four lines of code set the read write
         * attributes of the emplyee data type */
        public string empID { get; set; }
        public string fName { get; set; }
        public string lName { get; set; }
        public string cEducation { get; set; }

        // This function assigns data to the employee data type.
        public Employee(string id, string fname, string lname, string ceducation)
        {
            empID = id;
            fName = fname;
            lName = lname;
            cEducation = ceducation;
        }
       
        // This function sorts the array list.  
        public int CompareTo(Object obj)
           {
           if (obj is Employee)
               return this.empID.CompareTo((obj as Employee).empID);
           return 0;
           }
     }


        class Program
        {
            public static void Main()
            {
                ArrayList al = new ArrayList();  // create an instance of an ArrayList.
                /* Use the insert method to populate the ArrayList with instances of
                 * the employee class. */
                al.Insert(0, new Employee("00003", "John", "Smith", "a"));
                al.Insert(1, new Employee("00002", "Bill", "Shaffell", "az"));
                al.Insert(2, new Employee("00005", "Jane", "Williams", "p"));
                al.Insert(2, new Employee("00001", "Beth", "Longhorn", "z"));
                al.Insert(0, new Employee("00004", "Eddy", "Haskel", "w"));

                // Display the ArrayList after populating it..
                Console.WriteLine("The al ArrayList after populating it.\n");
                DisplayAL(al);

                al.Sort(); //Sort the ArrayList.

                // Display the ArrayList after sorting it.
                Console.WriteLine("The al ArrayList after sorting it.\n");
                DisplayAL(al);

                }
            private static void DisplayAL(IEnumerable al)
            {
                foreach (Employee emp in al)
                {
                    Console.Write(emp.empID + " - " + emp.lName + ", " + emp.fName + " " + emp.cEducation + "\n");
                }
                Console.ReadLine();
            }
        }

    Saturday, February 26, 2011 8:14 PM

Answers

  • I would recommand you to use a generic list<t> instead of ArrayList. It has all what has arraylist, and more. Sorting is on of them.

    Take a look at this example:

     public Form1()
        {
          InitializeComponent();
    
          List<Person> list = new List<Person>();
          Person[] persons = new Person[] { new Person(1, "George"), new Person(2, "Sara"), new Person(3, "Anna") };
          list.AddRange(persons);
          list = list.OrderBy(a => a.name).ToList();
    
          //OR: (use one or the other)!
          list.Sort((a1, a2) => a1.name.CompareTo(a2.name));
          
        }
    
        internal class Person
        {
          public int id { get; set; }
          public string name { get; set; }
    
          public Person(int _id, string _name)
          {
          this.id= _id;
            this.name=_name;
          }
        }
    Hope it gives  clue, and changes your mind to change arrayList with List<T>. Believe me, when you will start working with it, you will leave all others. I did :)

    Saturday, February 26, 2011 8:23 PM

All replies

  • I would recommand you to use a generic list<t> instead of ArrayList. It has all what has arraylist, and more. Sorting is on of them.

    Take a look at this example:

     public Form1()
        {
          InitializeComponent();
    
          List<Person> list = new List<Person>();
          Person[] persons = new Person[] { new Person(1, "George"), new Person(2, "Sara"), new Person(3, "Anna") };
          list.AddRange(persons);
          list = list.OrderBy(a => a.name).ToList();
    
          //OR: (use one or the other)!
          list.Sort((a1, a2) => a1.name.CompareTo(a2.name));
          
        }
    
        internal class Person
        {
          public int id { get; set; }
          public string name { get; set; }
    
          public Person(int _id, string _name)
          {
          this.id= _id;
            this.name=_name;
          }
        }
    Hope it gives  clue, and changes your mind to change arrayList with List<T>. Believe me, when you will start working with it, you will leave all others. I did :)

    Saturday, February 26, 2011 8:23 PM
  • You would be better off using List<Employee> instead of ArrayList.  This gives you type safe access, and would allow you to write:

     

         // Sort by firstname

         list.Sort( (l,h) => l.fName.CompareTo(r.fName)); 

     

    Or you could use linq:

     

        var sorted = list.OrderBy(employee => employee.fName);

     

     


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Saturday, February 26, 2011 8:25 PM
    Moderator
  • LOL :)

    We are both same thought  Reed. That means Im doing some progress, dont you think?

     

    Saturday, February 26, 2011 8:29 PM
  • LOL :)

    We are both same thought  Reed. That means Im doing some progress, dont you think?

     

    :)  Looks great!

     

     


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Saturday, February 26, 2011 8:41 PM
    Moderator
  • Thanks Mitja and Reed! Much easier this way.
    Saturday, February 26, 2011 9:52 PM
  • LoL, I`m just wondering if you have read the forum`s rules?

    a hint: your marked post does not include a thread`s solution, but someone elsees does, so..


    I hope it helps. If it does, mark the post as answered, if now, let me know about it...
    Saturday, February 26, 2011 10:02 PM