Home

Example of a Collection Class

     

Class: Student

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

namespace IntroductionCollections
{
    [Serializable]
    public class Student
    {
        private int stdn;
        private string fn;
        private string ln;
        private string gdr;

        public Student()
        {
            this.stdn = 0;
            this.fn = "John";
            this.ln = "Doe";
            this.gdr = "Hermaphrodite";
        }

        public Student(int number, string fName, string lName, string gender)
        {
            this.stdn = number;
            this.fn = fName;
            this.ln = lName;
            this.gdr = gender;
        }

        public int StudentNumber
        {
            get
            {
                return this.stdn;
            }
            set
            {
                this.stdn = value;
            }
        }

        public string FirstName
        {
            get { return this.fn; }
            set { this.fn = value; }
        }

        public string LastName
        {
            get { return this.ln; }
            set { this.ln = value; }
        }

        public string Gender
        {
            get { return this.gdr; }
            set { this.gdr = value; }
        }

        public override bool Equals(object obj)
        {
            Student std = (Student)obj;

            if ((this.stdn == std.stdn) &&
                (this.fn.Equals(std.fn)) &&
                (this.ln.Equals(std.ln)) &&
                (this.gdr.Equals(std.gdr)))
                return true;
            else
                return false;
        }

        public override string ToString()
        {
            return this.stdn.ToString() + " " + this.fn + " " + this.ln + " " + this.gdr;
        }
    }
}

Class: Students

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

namespace IntroductionCollections
{
    [Serializable]
    public class Students : IList
    {
        private int counter;
        private object[] studs;

        public Students()
        {
            counter = 0;
            studs = new object[5];
        }
        #region IList Members

        public void IncreaseCapacity()
        {
            Array.Resize<object>(ref studs, studs.Length + 5);
        }

        public int Add(object value)
        {
            // Check whether there is still room in
            // the array to add a new item
            if (counter < studs.Length)
            {
                // Since there is room, put the new item to the end
                studs[counter] = value;

                // increase the number of items
                counter++;
                // Return the index of the item that was added
                return counter - 1;
            } // Since the item could not be added, return a negative index
            else // if the index passed is too high ...
            {
                // ... then first increase the number of items
                IncreaseCapacity();
                // and proceed as above
                studs[counter] = value;
                counter++;
                return counter - 1;
            }
        }

        public void Clear()
        {
            counter = 0;
        }

        public bool Contains(object value)
        {
            bool found = false;

            for (int i = 0; i < counter; i++)
            {
                if (studs[i].Equals((Student)value) )
                {
                    found = true;
                    break;
                }
            }
            
            return found;
        }

        public int IndexOf(object value)
        {
            for (int i = 0; i < counter; i++)
                if( studs[i].Equals((Student)value) )
                    return i;
            return -1;
        }

        public void Insert(int index, object value)
        {
            // If the index is the same as the current number of items
            // then call Add() and proceed as if we want to add a new item
            if( index >= counter )
            {
                Add(value);
                return;
            }
            if( index >= 0 )
            {
                // Otherwise, push each item one position up to create
                // an empty space
                for (int i = (counter - 1); i > index - 1; i--)
                    studs[i + 1] = studs[i];

                // Then put the new item in the indicated position
                studs[index] = value;
                // Since the new item has been added, increase the 
                // current number of items
                counter++;
            }
        }

        public bool IsFixedSize
        {
            get { return false; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public void RemoveAt(int index)
        {
            if ((index >= 0) && (index < Count))
            {
                for (int i = index; i < Count - 1; i++)
                    studs[i] = studs[i + 1];
                counter--;
            }
        }

        public void Remove(object value)
        {
            RemoveAt(IndexOf(value));
        }

        public object this[int index]
        {
            get { return studs[index]; }

            set
            {
                studs[index] = value;
            }
        }

        #endregion

        #region ICollection Members

        public void CopyTo(Array array, int index)
        {
            array.CopyTo(studs, 0);
        }

        public int Count
        {
            get { return counter; }
        }

        public bool IsSynchronized
        {
            get { return true; }
        }

        public object SyncRoot
        {
            get { return this; }
        }

        #endregion

        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            return null;
        }

        #endregion

        #region Additional Routines

        // Checks whether the list is empty
        public bool IsEmpty()
        {
            if (counter == 0)
                return true;
            return false;
        }

        // Gets the first item in the list
        public object First
        {
            get
            {
                if (IsEmpty())
                    return null;

                return studs[0];
            }
        }

        // Gets the last item in the list
        public object Last
        {
            get
            {
                if (IsEmpty())
                    return null;

                return studs[counter - 1];
            }
        }

        // Replaces an existing item in the list with a new item
        // Equivalent to editing an existing item
        public void Replace(int position, object one)
        {
            if( position < 0 )
            {
                // Invalid position
                // Normally, we should throw an exception, such as IndexOutOfRange
                return;
            }

            if( position > counter )
            {
                // Invalid position
                // Normally, we should throw an exception, such as IndexOutOfRange
                return;
            }
            
            studs[position] = one;
        }

        // Changes the current position of an existing item
        // Moves the item from its current curIndex position to the new toIndex position
        public void Move(int curIndex, int toIndex)
        {
            if (curIndex < 0)
            {
                // Invalid starting index
                // Normally, we should throw an exception, such as IndexOutOfRange
                return;
            }
            if (curIndex > (counter - 1))
            {
                // Invalid starting index
                // Normally, we should throw an exception, such as IndexOutOfRange
                return;
            }
            if (toIndex < 0)
            {
                // Invalid end index
                // Normally, we should throw an exception, such as IndexOutOfRange
                return;
            }
            if (toIndex > (counter - 1))
            {
                // Invalid end index
                // Normally, we should throw an exception, such as IndexOutOfRange
                return;
            }
            if (curIndex == toIndex)
            {
                // Same index, do nothing
                return;
            }
  
            // Get the item at the starting position
            object objLower = this[curIndex];
            
            // Remove the item at the starting position
            RemoveAt(curIndex);
            // move the item to target position
            Insert(toIndex, objLower);
        }

        // Swaps the positions of two existing items
        // The first item goes to position posSecond
        // and the second item moves to position posFirst
        public void Exchange(int posFirst, int posSecond)
        {
            try
            {
                // Check that posFirst exists
                if (posFirst < 0)
                    throw new IndexOutOfRangeException("Invalid first index - Too low");
                // Check that posFirst exists
                if (posFirst > counter - 1)
                    throw new IndexOutOfRangeException("Invalid first index - Too high");
                // Check that posSecond exists
                if (posSecond < 0)
                    throw new IndexOutOfRangeException("Invalid second index - Too low");
                // Check that posSecond exists
                if (posSecond > counter - 1)
                    throw new IndexOutOfRangeException("Invalid second index - Too high");

                object objFirst = this[posFirst];
                object objSecond = this[posSecond];

                this[posFirst] = objSecond;
                this[posSecond] = objFirst;
            }
            catch (IndexOutOfRangeException)
            {
            }
        }

        #endregion

        public object[] ToArray()
        {
            object[] result = new object[counter];

            return studs.ToArray<object>();
        }
    }
}

Application

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace IntroductionCollections
{
    public partial class Exercise : Form
    {
        Students pupils;

        public Exercise()
        {
            InitializeComponent();
        }

        private void ResetTextBoxes()
        {
            this.txtStudentNumber.Text = "00000";
            this.txtFirstName.Text = "";
            this.txtLastName.Text = "";
            this.cbxGenders.SelectedIndex = 2;
            this.txtStudentNumber.Focus();
        }

        private void Exercise_Load(object sender, EventArgs e)
        {
            pupils = new Students();
        }

        private void ShowStudents()
        {
            lvwStudents.Items.Clear();

            for (int i = 0; i < pupils.Count; i++)
            {
                Student stud = (Student)pupils[i];

                ListViewItem lviStudent = lvwStudents.Items.Add(stud.StudentNumber.ToString());
                lviStudent.SubItems.Add(stud.FirstName);
                lviStudent.SubItems.Add(stud.LastName);
                lviStudent.SubItems.Add(stud.Gender);
            }

            /*
            foreach (Student std in pupils )
            {
                ListViewItem lviStudent = lvwStudents.Items.Add(std.StudentNumber.ToString()); // ((Student)pupils[i]).StudentNumber.ToString());
                lviStudent.SubItems.Add(std.FirstName);
                lviStudent.SubItems.Add(std.LastName);
                lviStudent.SubItems.Add(std.Gender);
            }
            */
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Student std = new Student();
            std.StudentNumber = int.Parse(this.txtStudentNumber.Text);
            std.FirstName = this.txtFirstName.Text;
            std.LastName = this.txtLastName.Text;
            std.Gender = this.cbxGenders.Text;
            this.pupils.Add((object)std);

            ShowStudents();
            ResetTextBoxes();
        }

        private void btnContains_Click(object sender, EventArgs e)
        {
            Student std = new Student(int.Parse(txtStudentNumber.Text), txtFirstName.Text, txtLastName.Text, cbxGenders.Text);

            object obj = (object)std;

            if( pupils.Contains(obj) )
                MessageBox.Show("The list contains the student");
            else
                MessageBox.Show("There is no student with that information");
        }

        private void btnIndexOf_Click(object sender, EventArgs e)
        {
            Student std = new Student(int.Parse(txtStudentNumber.Text), txtFirstName.Text, txtLastName.Text, cbxGenders.Text);
            int indexOf = 0;

            object obj = (object)std;

            if (pupils.Contains(obj))
            {
                indexOf = pupils.IndexOf(obj);
                MessageBox.Show("The index of this student is " + indexOf.ToString());
            }
            else
                MessageBox.Show("There is no student with that information");
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            Student std = (Student)pupils.First();

            if (std != null)
                MessageBox.Show(std.ToString());
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            Student std = (Student)pupils.Last();

            if (std != null)
                MessageBox.Show(std.ToString());
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            int position = int.Parse(txtInsertionPosition.Text);

            Student std = new Student();
            std.StudentNumber = int.Parse(this.txtStudentNumber.Text);
            std.FirstName = this.txtFirstName.Text;
            std.LastName = this.txtLastName.Text;
            std.Gender = this.cbxGenders.Text;
            this.pupils.Insert(position, (object)std);

            ShowStudents();
            ResetTextBoxes();
        }
    }
}

 

 
 

Home Copyright © 2010-2014, FunctionX