tags:

views:

115

answers:

4

Hi,

I have 2 classes and in the Persons class I want to add the ability of looping through the name properties of the Person collection using a foreach loop, like this:

foreach (string name in Persons.Names)
{
// do something
}

How would I do this?

These are my classes:

 class Person
    {
        public string Name
        {
            get;
            set;
        }

        public string Surname
        {
            get;
            set;
        }
    }

    class Persons : IEnumerable<Person>
    {
        List<Person> persons = new List<Person>();
        public IEnumerator<Person> GetEnumerator()
        {
            foreach (Person p in persons)
            {
                yield return p;
            }
        }

        System.Collections.IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public IEnumerator<string> Names
        {
            // implement looping through Name property of Person class
        }

        public Persons()
        {

        }

        public void Add( Person p )
        {
            persons.Add(p);
        }

        public string this[int index]
        {
            get { return this[index]; }
        }
    }
+2  A: 

Does this one work?

foreach (Person p in persons)
{
  yield return p.Name;
}

Cheers Matthias

Mudu
+4  A: 
    public IEnumerable<string> Names
    {
        get
        {
            foreach (Person p in persons)
            {
                yield return p.Name;
            }
        }
    }
Thomas Levesque
+7  A: 

The first loop can be implemented something like this:

foreach (Person p in Persons)
{
// do something with p.Name
}

You can implement the property something like:

public IEnumerator<string> Names
{
    get
    {
        foreach (Person p in persons)
        {
            yield return p.Name;
        }
    }
}

or using Linq:

public IEnumerator<string> Names
{
    get
    {
        return persons.Select(p => p.Name);
    }
}
Sander Rijken
There should be a get accessor squeezed in there as well
Oskar
+1 for completeness...
Thomas Levesque
+1  A: 

Have a look at this article here and here which would be of help to your question and situation.

Hope this helps, Best regards, Tom.

tommieb75