Ilist,icollection,ienumerable,ienumerator,iqueryable

Source: Internet
Author: User

Http://www.cnblogs.com/edison1105/archive/2012/07/30/2616082.html

1. First look at a simple example

int [] MyArray = {1, +,-343};             Myie = Myarray.getenumerator ();            Myie. Reset ();             (Myie. MoveNext ())            {                int i = (int) Myie. Current;                Console.WriteLine ("Value: {0}", I);            }
I'm sure a lot of people don't go through the myarray array like above, usually we do that.
            MyArray)                Console.WriteLine (item. ToString ());
In most cases, many people use the for and foreach to iterate over the array, but the syntax for the above is rarely used, but the exact origin of the foreach is blurred!
2. Understanding foreach

We all know to implement the foreach must implement IEnumerable and IEnumerator interface, only implement them, can realize traversal, so to talk about the origin of foreach, must be the two interfaces to clear point!

Here also want to explain a point is: if the two interfaces have a certain understanding, as long as the implementation of the GetEnumerator method can, and do not need to implement the IEnumerable interface, this is only for the two interfaces have a certain understanding of the friends!

2.1 IEnumerable

The purpose of this is to make an object that implements this interface an enumerable type.

The IEnumerable interface contains a GetEnumerator method that returns a value of IEnumerator type! The code is as follows:

    IEnumerable     {        };         GetEnumerator ()        {            colors. GetEnumerator ();        }    }

Then we can do this when the client makes the call!

            mycolors colors = new mycolors();             colors)                Console.WriteLine (item);
This can be used to implement the object of this interface foreach traversal, is such a simple case, there may be some people will have doubts, we implemented the IEnumerable interface but did not implement the IEnumerator interface, But don't we say that only the two interfaces are implemented for a foreach traversal? It can be said that when using Forach to traverse, the compiler will go to the object's class to find the GetEnumerator method, find this method and return the object of this IEnumerator (enumerator), and my return is "colors." GetEnumerator () ", is an array object calls itself in the" GetEnumerator "method, so that the array itself implements the IEnumerator interface, then two interfaces are implemented, not a good implementation of the foreach traversal, In fact, when implementing a traversal enumerator, the compiler automatically calls the method in the class that implements the enumerator in the array.
2.2  IEnumerator

The function of the interface: to implement an enumerable, first look at the definition of the interface:

Contains a property of two methods

movenext→ moves the current item to the next item (similar to an index value) and returns a bool value that checks whether the current item is outside the enumerator range!

current→ gets the value of the current item and returns the type of the object (this will involve packing and unpacking problems → When the generics are referred to later)!

reset→, as the name implies, restores some values to their default values, such as returning the current item to the default state value!

Public class Myienumerator:IEnumerator{public Myienumerator (string[] colors) {this.colors = new string[Colors.            Length]; for (int i = 0; i < this. Colors. Length; i++) This. Colors[i] = colors[i];        } string[] colors; //define an array to store the data int position =-1; //define the default value of the current item, that is, the index value, the first to know the index of the array starts with "0",//How to set the default to "1", and finally to understand that this setting is reasonable! public Object Current//Get the corresponding value according to the current item{            Get{return colors[position]; //Returns the value of the current item, but does a boxing operation! }} public bool MoveNext ()//Move to next item{if (Position < colors. LENGTH-1)//This is the setting of the default value of-1 based on{position++; return True; }          Else{return False; }        }        //Resets the value of the current item, reverting to the default value of public voidReset () { this. Position =-1; }    }
The GetEnumerator method in the IEnumerable interface described above is to get the enumerator to traverse, and when we do not create our own class to iterate through the enumerator, we are using the array traversal method (the enumerable type of the array and the enumerator are discussed in the next article). But this is sometimes not suitable for us, we need to customize a more suitable for ourselves, so we want to create our own enumerator class (that is, the above code), the 3rd and 4th code together (change a little bit of code), as follows:
Public         class mycolors   //: IEnumerable        {            };             GetEnumerator ()                {myienumerator(colors);            }        }
3. About enumerable types and enumerators

① enumerable type → implement IEnumerable interface, you can not directly implement this interface, but there must be a GetEnumerator method, the return value type must be the IEnumerator type, that is, the 4th of the last piece of code in the interface annotation that way!

② enumerator → Implement IEnumerator interface, implement all methods, first, call GetEnumerator returns an enumerator of type IEnumerator, then the compiler implicitly calls the implementation of the methods and properties in the IEnumerator Class!

Summary: So the implementation of the foreach traversal, must reach the above two conditions to traverse the object, they can be written together can also be separated, preferably separate, separation of duties, a class do one thing is always good! It also satisfies the design principle of object-oriented single accusation.

The following code example demonstrates how to implement the IEnumerable and IEnumerator interfaces of a custom collection (code from MSDN)

usingsystem;usingsystem.collections;usingsystem.collections.generic;usingsystem.linq;usingsystem.text;usingSystem.threading.tasks;namespaceconsoleapplication1{public class Person{public person (string fName, StringlName) { This. firstName = FName; this. lastName = LName; } public StringFirstName; public stringLastName; } public class people:IEnumerable{private person[] _people; Public people ( person[] parray) {_people = new person[Parray.length]; for (inti = 0; i < parray.length; i++)            {_people[i] = Parray[i]; }} IEnumerator IEnumerable. GetEnumerator () {return (IEnumerator) GetEnumerator (); } public PeopleenumGetEnumerator () {return new Peopleenum(_people); }} public class Peopleenum:IEnumerator{ Public person[] _people; //enumerators is positioned before the first element//until the first MoveNext () call. intposition =-1; Public Peopleenum ( person[] list)        {_people = list; } public boolMoveNext () {position++; Return(Position < _people.        Length); } public voidReset () {position =-1; } Object IEnumerator. Current {Get{returnCurrent ; }} Public personCurrent {Get{                Try{return_people[position]; } catch (IndexOutOfRangeException) {throw new InvalidOperationException(); } }}} Class Program{static void Main (String[] args) {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 inpeoplelist) Console.WriteLine (P.firstname + ""+ p.lastname); }    }}

No picture, no truth.

I am not the title party, the following introduction ilist,icollection,iqueryable

1.IList is the descendant of the ICollection interface and is the base interface for all non-generic lists. There are three categories of IList implementations: read-only, fixed-size, and variable-size. Read-only IList cannot be modified. Fixed-size IList does not allow the addition or removal of elements, but allows the modification of existing elements. The variable-size IList allows you to add, remove, and modify elements.

2. TheICollection interface is the base interface for classes in the System.Collections namespace. The ICollection interface extension ienumerable;idictionary and IList are more specialized interfaces for extended ICollection. The IDictionary implementation is a collection of key/value pairs, such as the Hashtable class.  An IList implementation is a collection of values whose members can be accessed through an index, such as the ArrayList class.  Some collections, such as the Queue class and the Stack class, restrict access to their elements, and they implement the ICollection interface directly. If both the IDictionary interface and the IList interface do not meet the requirements of the required collection, the new collection class is derived from the ICollection interface for increased flexibility. Defines the size, enumerator, and synchronization methods for all non-generic collections.

3.IQueryable provides the ability to compute queries for a specific data source that does not specify a data type, and the IQueryable interface is implemented by the query provider. The interface can only be implemented by a provider that implements IQueryable (of T) at the same time. If the provider does not implement IQueryable (of T), you cannot use the standard query operator with the provider data source. The IQueryable interface inherits the IEnumerable interface so that the results of the query can be enumerated when the former represents a query. Enumeration enforces the expression tree associated with the IQueryable object. The definition of execution expression tree is specific to the query provider. For example, it might involve converting an expression tree to a query language that is appropriate for the underlying data source. Queries that do not return enumerable results are executed when the Execute method is called.

Sorry, here is a rough introduction, all said I am lazy, tomorrow also to work, next time to continue ...

Ilist,icollection,ienumerable,ienumerator,iqueryable

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.