开发者

Implementing IEnumerable question

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&g开发者_运维问答t; 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]; }
        }
    }


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);
    }
}


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


Does this one work?

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

Cheers Matthias


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜