Write a generic set type by yourself, which can be added and traversed.

Source: Internet
Author: User

Write a generic set type by yourself, which can be added and traversed.


In "C # List <T> how to store elements", I analyzed the source code of List <T> and learned how List <T> stores elements. This time, you can customize a generic set type to add elements and support traversal.

 

This generic set type requires an element adding method. When adding an element, consider: When the added element exceeds the current array capacity, let the array expand; to support loop traversal, the generic set type must provide an iterator (implementing the IEnumerator interface ).

    public class MyList<T>
    {
        T[] items = new T[5];
        private int count;
        public void Add(T item)
        {
            if(count == items.Length)
               Array.Resize(ref  items, items.Length * 2);
            items[count++] = item;
        }
        public IEnumerator<T> GetEnumerator()
        {
            return new MyEnumeraor(this);
        }
        class MyEnumeraor : IEnumerator<T>
        {
            private int index = -1;
            private MyList<T> _myList;
            public MyEnumeraor(MyList<T> myList)
            {
                _myList = myList;
            }
            public T Current
            {
                get
                {
                    if (index < 0 || index >= _myList.count)
                    {
                        return default(T);
                    }
                    return _myList.items[index];
                }
            }
            public void Dispose()
            {
                
            }
            object System.Collections.IEnumerator.Current
            {
                get { return Current; }
            }
            public bool MoveNext()
            {
                return ++index < _myList.count;
            }
            public void Reset()
            {
                index = -1;
            }
        }
    }

○ The generic collection type maintains a T-type generic array.
○ The private field count is used to count. Each time an element is added, the count is incremented by 1.
○ The addition method considers that when the count is equal to the length of the current element, the array will be resized to twice the current size.
○ The iterator implements the IEnumerator <T> interface.

 

Client call.

    class Program
    {
        static void Main(string[] args)
        {
            MyList<int> list = new MyList<int>();
            list.Add(1);
            list.Add(2);
            foreach (int item in list)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }

 

What is the difference between IEnumerable and IEnumerator?
In fact, the IEnumerator iterator is actually used to execute iterations. The IEnumerable interface provides a method to return the IEnumerator iterator.

public interface IEnumerable
{
    IEnumerator GetEnumerator();
}

In C #, put entity Class A in list generic set list1. What should I do if I combine the values of each field in A during the extraction?

Hello, your problem is only to traverse the set:
Assume that list2 is a generic set of B.

Reference code:
Foreach (A a1 in list1 ){
B b1 = new B ();
B1.a = a1.a;
// All fields in b1 are assigned according to different bcd values.
B1.e = a1.e;
List2.add (b1 );
}

C # traversal of generic Sets

There are three types
It's easy. Here is an example:
1. Declare a Dictoinary <key, value> generic set first
Create a Student Class Object Student stu = new Student () (in this class
There is a name attribute)
Dictionary <student. name, Student> students = new Dictionary <student. name, Student> ();
Students. Add (stu );
2. Start traversing
(1) Stuent objects can be traversed using values.
Foreach (Student stu in students. values)
{}
(2) You can also use the key to traverse student. name.
Foreach (string key in students. keys)
{}
3. In addition, list <T> generic sets share the same principle. However,
It must be indexed
For example
List <Student> stu = new list <Student> ();
Stu (1). name;
Hope you understand

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.