Implement an Enumerable Collection - CSharp Collection

CSharp examples for Collection:Iterator

Description

Implement an Enumerable Collection

Demo Code


using System;/*  w  w  w  .ja  v  a 2  s .  co m*/
using System.Collections.Generic;

    public class TeamMember
    {
        public string Name;
        public string Title;

        public TeamMember(string name, string title)
        {
            Name = name;
            Title = title;
        }

        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, Title);
        }
    }

    public class Team
    {
        private List<TeamMember> teamMembers = new List<TeamMember>();
        public IEnumerator<TeamMember> GetEnumerator()
        {
            foreach (TeamMember tm in teamMembers)
            {
                yield return tm;
            }
        }
        public IEnumerable<TeamMember> Reverse
        {
            get
            {
                for (int c = teamMembers.Count - 1; c >= 0; c--)
                {
                    yield return teamMembers[c];
                }
            }
        }
        public IEnumerable<TeamMember> FirstTwo
        {
            get
            {
                int count = 0;

                foreach (TeamMember tm in teamMembers)
                {
                    if (count >= 2)
                    {
                        // Terminate the iterator.
                        yield break;
                    }
                    else
                    {
                        // Return the TeamMember and maintain the iterator.
                        count++;
                        yield return tm;
                    }
                }
            }
        }
        public void AddMember(TeamMember member)
        {
            teamMembers.Add(member);
        }
    }

class MainClass
    {
        public static void Main()
        {
            Team team = new Team();
            team.AddMember(new TeamMember("A", "X"));
            team.AddMember(new TeamMember("B", "Y"));
            team.AddMember(new TeamMember("C", "W"));

            foreach (TeamMember member in team)
            {
                Console.WriteLine("  " + member.ToString());
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Enumerate using the FirstTwo iterator:");
            foreach (TeamMember member in team.FirstTwo)
            {
                Console.WriteLine("  " + member.ToString());
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Enumerate using the Reverse iterator:");
            foreach (TeamMember member in team.Reverse)
            {
                Console.WriteLine("  " + member.ToString());
            }
        }
    }

Result


Related Tutorials