SoFunction
Updated on 2025-04-06

Introduction and implementation of custom collections in C#

Introduction

The IEnumerable interface is very simple, including only an abstract method GetEnumerator(), which returns an IEnumerator object that can be used to iterate over the collection. For all array traversals, it comes from the IEnumerable interface.
What are the IEnumerator objects? It is a real collection accessor. Without it, you cannot use the foreach statement to traverse a collection or array, because only the IEnumerator object can access items in the collection. If even the items in the collection cannot be accessed, then it is impossible to traverse the collection a loop.

1. Foreach case in IEnumerable

    public static void Test3()
    {
        MyInt temp = new MyInt();
        foreach (int item in temp)
        (item);
    }
    //Foreach must implement the interface between IEnumerable and IEnumerator    public class MyInt : IEnumerable
    {
        int[] temp = { 1, 32, 43, 343 };

        public IEnumerator GetEnumerator()
        {
            return ();
        }
    }

Equivalent to the following code:

    public static void Test1()
    {
        int[] myArray = { 1, 32, 43, 343 };
        //Get the enumeration number to traverse        IEnumerator myie = ();
        //Reset the current item is equivalent to moving the pointer to the initial position: position = -1; At the beginning, I understand that the index of the array starts with "0"        ();
        //Move a index forward, return to the Bool type, and determine whether the subscript is exceeded.        while (())
        {
            int i = (int);//Convert from Object to corresponding type            ("Value: {0}", i);
        }
    }

Contains one attribute and two methods
MoveNext: Move the current item to the next item (similar to the index value), and return a bool value. This bool value is used to check whether the current item exceeds the range of the enumeration number!
Current: Get the value of the current item and return the type of object!
Reset: As the name implies, it means restoring some values ​​to the default value, such as restoring the current item to the default state value!

2. Lamda isIEnumerableCase

// lamda expression query in array        public static void Test2()
        {
            List<string> fruits =
              new List<string> { "apple", "passionfruit", "banana", "mango",
                    "orange", "blueberry", "grape", "strawberry" };
            //List<string> query = (fruit =>  < 6).ToList();
            IEnumerable<string> query = (fruit =>  < 6);
            foreach (string fruit in query)
                (fruit);
        }

Only filter out values ​​with length less than 6 in List and print them out.

Implementing the IEnumerable and IEnumerator interfaces for custom collections

namespace ConsoleApplication1
{
    //Define Person class    public class Person
    {
        //initialization        public Person(string fName, string lName)
        {
             = fName;
             = lName;
        }

        //Class Member        public string firstName;
        public string lastName;
    }

    //Implement the interface    public class People : IEnumerable
    {
        private Person[] _people;
        public People(Person[] pArray)
        {
            _people = new Person[];

            for (int i = 0; i < ; i++)
            {
                _people[i] = pArray[i];
            }
        }

        IEnumerator ()
        {
            return (IEnumerator)GetEnumerator();
        }

        //Get enumeration number        public PeopleEnum GetEnumerator()
        {
            return new PeopleEnum(_people);
        }
    }

    public class PeopleEnum : IEnumerator
    {
        public Person[] _people;

        // Enumerators are positioned before the first element
        // until the first MoveNext() call.
        int position = -1;

        public PeopleEnum(Person[] list)
        {
            _people = list;
        }

        //Push down the index and return the Bool type value        public bool MoveNext()
        {
            position++;
            return (position < _people.Length);
        }

        //Reset the default index position, the default index is 0        public void Reset()
        {
            position = -1;
        }

        object 
        {
            get
            {
                return Current;
            }
        }

        //Current index value        public Person Current
        {
            get
            {
                try
                {
                    return _people[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Instantiate Person            Person[] peopleArray = new Person[3]
            {
                new Person("John", "Smith"),
                new Person("Jim", "Johnson"),
                new Person("Sue", "Rabon"),
            };

            People peopleList = new People(peopleArray);
            foreach (Person p in peopleList)
                ( + " " + );
        }
    }
}

This is all about this article about the IEnumerable interface and implementing custom collections in C#. I hope it will be helpful to everyone's learning and I hope everyone will support me more.