?
Solved

Iterating through a class

Posted on 2005-04-28
15
Medium Priority
?
339 Views
Last Modified: 2012-05-05
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
Comment
Question by:Kokas79
  • 6
  • 3
  • 3
  • +2
14 Comments
 
LVL 3

Assisted Solution

by:chintan_vaishya
chintan_vaishya earned 240 total points
ID: 13884348
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
 

Author Comment

by:Kokas79
ID: 13884486
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
 
LVL 11

Assisted Solution

by:jatinderalagh
jatinderalagh earned 240 total points
ID: 13885323
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 11

Expert Comment

by:jatinderalagh
ID: 13885424
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
 

Author Comment

by:Kokas79
ID: 13885531
thanks a lot...i'm not familiar with this. I will study it, use it and come back to you :)
0
 
LVL 1

Expert Comment

by:djhoen
ID: 13886405
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
 

Author Comment

by:Kokas79
ID: 13886586
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
 
LVL 1

Expert Comment

by:djhoen
ID: 13886747
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
 

Author Comment

by:Kokas79
ID: 13887085
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
 
LVL 11

Expert Comment

by:jatinderalagh
ID: 13887234
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
 
LVL 1

Assisted Solution

by:djhoen
djhoen earned 240 total points
ID: 13887440
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
 

Author Comment

by:Kokas79
ID: 13887534
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
 
LVL 3

Accepted Solution

by:
Diego Pazos earned 480 total points
ID: 13897396
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
 

Author Comment

by:Kokas79
ID: 14051685
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

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question