Differences between IEnumerable, ICollection, IList, IQueryable, IQueryable in C #

Source: Internet
Author: User

One: a simple example

Int[] MyArray = {1, +, 343};            IEnumerator Myie = Myarray.getenumerator ();            Myie. Reset ();            while (Myie. MoveNext ())            {                int i = (int) Myie. Current;                Console.WriteLine ("Value: {0}", i);            }

usually we do this:

foreach (int item in MyArray)  Console.WriteLine (item. ToString ());

using for and foreach to iterate through the array, but for the above syntax is very little, but the specific origin of foreach is still very vague! "

Second: Understanding foreach

To implement the foreach must be implemented IEnumerable and IEnumerator interface, only implement them, to achieve traversal, so to speak the origin of foreach, must be the two interfaces to clear point!

If you have a certain understanding of the two interfaces, just implement that GetEnumerator method, and do not need to implement the IEnumerable interface

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: Public    class mycolors:ienumerable    {        string[] colors = {"Red", "Yellow", "Biue"};        Public IEnumerator GetEnumerator ()        {            return colors. GetEnumerator ();        }    } Then we can do this when the client makes the call!            mycolors colors = new MyColors ();            foreach (string item in Colors)                Console.WriteLine (item);

The array itself implements the IEnumerator interface, then two interfaces are implemented, not a good implementation of the foreach traversal, in fact, when the implementation of the traversal enumerator, the compiler will automatically call the array to implement the enumerator in the class method.

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, returning the type of an object

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.co Lors = new string[colors.            Length];        for (int i = 0; i < this.colors.Length; i++) this.colors[i] = colors[i];        } string[] colors;      Defines an array that is used to store data int position =-1;            Defines the default value of the current item, which is the index value, beginning with the index of the array starting with "0", public object current//get the corresponding value {get          {return colors[position];            Returns the value of the current item, but does a boxed operation! }} public bool MoveNext ()//move to the next item {if (Position < colors.                LENGTH-1)//This is the setting of the default value of-1 according to {position++;          return true;          } else {return false;        }}//Resets the value of the current item, reverts to the default value of public void Reset () {this.position =-1; }} The GetEnumerator method in the IEnumerable interface mentioned above is to get the enumerator to traverse,When we did not create our own class to iterate through the enumerator, we used the array traversal method of the enumerator, 
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 bit of code), as follows: public class MyColors//: IEn umerable {string[] colors = {"Red", "Yellow", "Biue"}; Public IEnumerator GetEnumerator () {return new myienumerator (colors); } }

3. About enumerable 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

Using system;using system.collections;using system.collections.generic;using system.linq;using System.Text;using System.threading.tasks;namespace consoleapplication1{public class Person {public person (string fName, Strin            G lName) {this.firstname = FName;        This.lastname = LName;        } public string FirstName;    public string LastName;        } public class People:ienumerable {private person[] _people;            Public people (person[] parray) {_people = new person[parray.length];            for (int i = 0; i < parray.length; i++) {_people[i] = Parray[i];        }} IEnumerator Ienumerable.getenumerator () {return (IEnumerator) GetEnumerator ();        } public Peopleenum GetEnumerator () {return new peopleenum (_people);      }} public class Peopleenum:ienumerator {public person[] _people;  Enumerators is positioned before the first element//until the first MoveNext () call.        int position =-1;        Public Peopleenum (person[] list) {_people = list;            } public bool MoveNext () {position++; Return (Position < _people.        Length);        } public void Reset () {position =-1;            } object IEnumerator.Current {get {return current;                    }} public person current {get {try {                return _people[position]; } catch (IndexOutOfRangeException) {throw new InvalidOperationException (                ); }}}} class program {static void Main (string[] args) {person[] Peo            Plearray = new Person[3] {    New Person ("John", "Smith"), the new person ("Jim", "Johnson"), the new person ("Sue", "Rabon"),            };            People peoplelist = new people (Peoplearray);        foreach (person p in Peoplelist) Console.WriteLine (P.firstname + "" + p.lastname); }    }}

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. The ICollection 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.

Differences between IEnumerable, ICollection, IList, IQueryable, IQueryable in C #

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.