Populate Enumerable.ToList with one line of code

Viewed 89

Please see the person class below:

public class Person
    {
        int _id { get; set; }
        string _name { get; set; }

        public Person (int id, string name)
        {
            _id = id;
            _name = name;
        }

        public Person()
        {
        }

        public IEnumerable<Person> GetPeople()
        {
            _id = 1;
            _name = "James";
            yield return this;

            _id = 2;
            _name = "Michael";
            yield return this;

            _id = 3;
            _name = "Sarah";
            yield return this;
        }
    }

and the client code below:

Person p1 = new Person();
IEnumerable<Person> personEnumerable = p1.GetPeople();
List<Person> personList = personEnumerable.ToList();

Why does PersonList contain three entries for Sarah after this has run? What is the best way to populate personList in the client?

2 Answers
Related