• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 342
  • Last Modified:

Iterating through a class

Hello

I have a class Employee and i was to iterate through it as a collection. I just have some problems with the code and need to rewrite a little bit. Have a look please:

class Class1
      {
            static void Main(string[] args)
            {
                  Employee e1 = new Employee("Kostas", "07786615014");
                  Employee e2 = new Employee("Shirley", "07778517266");
                  e1.Add(e1);
                  e2.Add(e2);
                  foreach (Employee e in al)
                  {
                        e.ToString();
                  }
            }
      }

      class Employee : IEnumerable
      {
            string name,phone;
            public Employee (string n, string p)
            {
                  this.name = n;
                  this.phone = p;
            }

            ArrayList al = new ArrayList();
            public void Add(Employee e)
            {
                  this.al.Add(e);
            }

            public override string ToString()
            {
                  return name + " " + phone + "\n";
            }


                      public IEnumerator GetEnumerator()
            {
                  return this.al.GetEnumerator();
            }
      }

I'm not exactly sure what to do with the arraylist...i have it in the employee class, but how should i use it in main?
0
Kokas79
Asked:
Kokas79
  • 6
  • 3
  • 3
  • +2
4 Solutions
 
chintan_vaishyaCommented:
Hi,

This will give u clear idea.


public class MyClass
      {
            public string Name;
            public int Age;
            
            //Default constructor
            public MyClass()
            {
            }

            //This parametrised constructor will assign value to this class data members.
            public MyClass(string name,int age)
            {
                  this.Name=name;
                  this.Age=age;
            }

      }

      public class Iterator:IEnumerator,IEnumerable
      {
            // Instantiating a collection of MyClass type.
            private MyClass[] ClassArray;
            int Cnt;

            public Iterator()
            {
                  //Assigning values in default constructor
                  ClassArray=new MyClass[4];
                  ClassArray[0] = new MyClass("Kith",23);
                  ClassArray[1] = new MyClass("Smith",30);
                  ClassArray[2] = new MyClass("Geo",19);
                  ClassArray[3] = new MyClass("Greg",14);

            }
            
            //Defanision for IEnumerator.Reset() method.
            public void Reset()
            {
                  
                  Cnt=-1;
            }

            //Defanision for IEnumerator.MoveNext() method.
            public bool MoveNext()
            {
                  return (++ Cnt < ClassArray.Length);
                  
            }

            //Defanision for IEnumerator.Current Property.
            public object Current
            {
                  get
                  {
                        return ClassArray[Cnt];
                  }
            }
            //Defanision for IEnumerable.GetEnumerator() method.
            public IEnumerator GetEnumerator()
            {
                  return (IEnumerator)this;
            }

            static void Main()
            {
                  //Now this instance will contain a collection of MyClass Tyes
                  Iterator It=new Iterator();
                  //Am trying to access like normal array
                  foreach(MyClass MY in It)
                  {
                        Console.WriteLine("Name : "+MY.Name.ToString());
                        Console.WriteLine("Age : "+MY.Age.ToString());

                  }
            }

      }

Hope this helps.
Good luck.
Chintan.
0
 
Kokas79Author Commented:
So your Iterator class acts like a collection by implementing those interfaces?

What if i dont want to hard-code those values when creating an Iterator object? I'm saying this cause ultimately i want to build a web application where i will have a method that uses a stored procedure and returns rows with data like name,phonenumber etc.
So i wont know from the beginning which employees i will have, that's why i used an arraylist.
One more thing...why did u put the main method in the Iterator class?
also...something that bothers me...if we have an arraylist or array in that class why do we implement the interfaces? cant we iterate through the array without them?
I know i'm asking lots of questions..i will raise the points.
0
 
jatinderalaghCommented:
How about using collection base class for this purpose. using Collection base you will be able to achieve all the benefits which you need from collections. Say for example: --


public class Employee
      {
            public string Name;
            public int Age;
         
            //Default constructor
            public Employee()
            {
                  Name = string.Empty;
            }

            //This parametrised constructor will assign value to this class data members.
            public Employee(string name,int age)
            {
                  this.Name=name;
                  this.Age=age;
            }

      }

      
      public class Employees : CollectionBase  
      {

            public Employee this[ int index ]  
            {
                  get  
                  {
                        return( (Employee) List[index] );
                  }
                  set  
                  {
                        List[index] = value;
                  }
            }

            public int Add( Employee value )  
            {
                  return( List.Add( value ) );
            }

            public int IndexOf( Employee value )  
            {
                  return( List.IndexOf( value ) );
            }

            public void Insert( int index, Employee value )  
            {
                  List.Insert( index, value );
            }

            public void Remove( Employee value )  
            {
                  List.Remove( value );
            }

            public bool Contains( Employee value )  
            {
                  // If value is not of type Employee, this will return false.
                  return( List.Contains( value ) );
            }

            protected override void OnInsert( int index, Object value )  
            {
                  // Insert additional code to be run only when inserting values.
            }

            protected override void OnRemove( int index, Object value )  
            {
                  // Insert additional code to be run only when removing values.
            }

            protected override void OnSet( int index, Object oldValue, Object newValue )  
            {
                  // Insert additional code to be run only when setting values.
            }

            protected override void OnValidate( Object value )  
            {
                  if ( value.GetType() != Type.GetType("Employee") )
                        throw new ArgumentException( "value must be of type Employee.", "value" );
            }

      }
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
jatinderalaghCommented:
The benefits of using collectionbase as base class

Employees empList = new Employees();
                  empList.Add(new Employee("jatinder",27));
                  empList.Add(new Employee("bob",26));
                  empList.Add(new Employee("test",28));

                  // iterate through the collection
                  foreach(Employee emp in empList)
                  {
                        Console.WriteLine("Name {0} , Age {1}",emp.Name,emp.Age);
                  }

                  // get the object directly using index
                  Employee firstEmployee = empList[0];

                  // Check for the containment
                  empList.Contains(firstEmployee);
0
 
Kokas79Author Commented:
thanks a lot...i'm not familiar with this. I will study it, use it and come back to you :)
0
 
djhoenCommented:
Hi Kokas79 -

Here is what has worked for me.  First a couple of questions.  Why do you have an ArrayList of Employees in the Employee class?  If the Employee class' purpose is do define one Employee at a time, it doesn't make sense to have an ArrayList of Employees in your Employee class, especially if you want to iterate through the collection.  Everytime you instantiate a new Employee, that arraylist is empty, so it would only add one employee (the one you just instantiated).  A solution would be to keep an ArrayList of Employees in your Class1 class.  When you create an instance of an Employee, add it to you your arraylist (the arraylist that you have defined in the Class1 class).  You can then iterate through your Class1 Employee ArrayList and have access to each employee's info.

Good Luck!

djhoen
0
 
Kokas79Author Commented:
Thanks for pointing that out djhoen, you just earned urself some points! I will try to do the collection based solution as it is more elegant, what do you think?
0
 
djhoenCommented:
I have used both in the past, but in your case, you don't have to use the collection based class.  Your arraylist of Employees is your collection.  You can access any of the public methods or properties you create when you iterate through your arraylist.

For example,
foreach (Employee e in empAL)
{
  string x = e.ToString();
}

All of the benefits from a collection (stated in jatinderalagh's post) are available with an ArrayList.
0
 
Kokas79Author Commented:
So you make me ask the obvious question...why go through all that hassle if it is so easy with the ArrayList? For example..have a look at this link.

http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=16

He's got his array in the library class so he can iterate, why bother with the interface? I just dont know when u should do what and i had an interview recently where i could do much better if i knew!
0
 
jatinderalaghCommented:
It's simple OOPS rule.

Moving from generalization to specialization depending on the need.

That's why the collection are written as specialized classes. Where the ArrayList is more generalized class.
0
 
djhoenCommented:
jatinderalagh has some good points.  One other advantage of IEnumerable is that when you are iterating through, you can see what your current index is (which also wouldn't be hard to implement with an arraylist).  Other than that, I can't really think of any other big advantages to using IEnumerable.  Another advantage of using an Arraylist is that you can add any type of object to the arraylist and then use rtti to identify what they are.  
0
 
Kokas79Author Commented:
Yeah i thought of that too djhoen...whatever interface's methods you override you can simply create similar ones in your class, that's why i was wondering. I didn't know you can add any kind of object, useful. But again you can add a validation method and make it behave like the CollectionBase :)

Thanks jatinderalagh for that...makes it clearer in my head.
0
 
Diego PazosCommented:
First of all, you won't get much output by calling e.ToString() on its own. You should do a Console.WriteLine or MessageBox.Show, depending on the type of program you're going for.

Then, I didn't really understand what you were trying to do. If what you want is to create a class that contains employees and allows you to iterate through it, this is what you want.

This defines a 'Company' class that has an 'Add' method for adding Employees, and implements IEnumerable for running through it.

class Program {
        static void Main(string[] args) {
            Company C = new Company();
            C.Add(new Employee("Kostas", "07786615014"));
            C.Add(new Employee("Shirley", "07778517266"));
            foreach (Employee e in C) {
                Console.WriteLine(e.ToString());
            }
            Console.Read();
        }
    }

    class Employee {
        string name, phone;
        public Employee(string n, string p) {
            this.name = n;
            this.phone = p;
        }

        public override string ToString() {
            return name + " " + phone + "\n";
        }
    }

    class Company : IEnumerable {
        ArrayList al = new ArrayList();
        public void Add(Employee e) {
            this.al.Add(e);
        }

        public IEnumerator GetEnumerator() {
            return this.al.GetEnumerator();
        }
    }
0
 
Kokas79Author Commented:
Sorry I had totally forgotten about this after returning from holidays!

I apologise to all the people who posted. I will close this question now.


Thanks again
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 6
  • 3
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now