C # advanced programming (7) -- Iteration

Source: Internet
Author: User

. NET uses the IEnumerator interface and the IEnumerable interface (and their generic versions) to implement the iterator mode. iteration is the core of LINQ.
The interface is defined as follows:
[Csharp]
Public interface IEnumerable
{
IEnumerator GetEnumerator ();
}
 
Public interface IEnumerator
{
Object Current {get ;}
Bool MoveNext ();
Void Reset ();
}
 
Public interface IEnumerable <out T>: IEnumerable
{
IEnumerator <T> GetEnumerator ();
}
 
Public interface IEnumerator <out T>: IDisposable, IEnumerator
{
T Current {get ;}
}

I. C #1 Implementation Iteration Method
C #1 implements iteration through the interface. The following is an example. You can specify the Starting sequence to iterate the set. Some of the notes are reflected in the annotations.
[Csharp]
Public class IterationSample: IEnumerable <string>
{
String [] values;
Int startingPoint;
 
Public IterationSample (string [] values, int startingPoint)
{
This. values = values;
This. startingPoint = startingPoint;
}
Public IEnumerator <string> GetEnumerator ()
{
// This is important to return a new instance of iterator
// So that each foreach loop will have its own iterator.
Return new IterationSampleIterator (this );
}
 
// Class that implement IEnumerable <T> must also implement IEnumerable,
// Here is a workaround to implement GetEnumerator method that defined
// In both IEnumerable <T> and IEnumerable.
IEnumerator IEnumerable. GetEnumerator ()
{
Return GetEnumerator ();
}
 
// Inner class can access to private members of its parent class.
Class IterationSampleIterator: IEnumerator <string>
{
IterationSample parent;
Int position;
 
Internal IterationSampleIterator (IterationSample parent)
{
This. parent = parent;
Position =-1;
}
 
Public bool MoveNext ()
{
If (position! = Parent. values. Length)
{
Position ++;
}
 
Return position <parent. values. Length;
}
 
Object IEnumerator. Current
{
Get {return Current ;}
}
 
Public string Current
{
Get
{
If (position =-1 |
Position = parent. values. Length)
{
Throw new InvalidOperationException ();
}
Int index = position + parent. startingPoint;
Index = index % parent. values. Length;
Return parent. values [index];
}
}
 
Public void Reset ()
{
Position =-1;
}
 
Public void Dispose ()
{
}
}
}
 
String [] values = {"a", "B", "c", "d", "e "};
IterationSample collection = new IterationSample (values, 3 );
Foreach (object x in collection)
{
Console. WriteLine (x );
}

II. C #2 Implementation Iteration Method
C #2 provides the yield keyword, which greatly simplifies iteration implementation code. The yield method is used to rewrite the above implementation.
[Csharp]
Public class IterationSample: IEnumerable <string>
{
String [] values;
Int startingPoint;
 
Public IterationSample (string [] values, int startingPoint)
{
This. values = values;
This. startingPoint = startingPoint;
}
Public IEnumerator <string> GetEnumerator ()
{
For (int index = 0; index <values. Length; index ++)
{
Yield return values [(index + startingPoint) % values. Length];
}
}
 
// Class that implement IEnumerable <T> must also implement IEnumerable,
// Here is a workaround to implement GetEnumerator method that defined
// In both IEnumerable <T> and IEnumerable.
IEnumerator IEnumerable. GetEnumerator ()
{
Return GetEnumerator ();
}
}
 
String [] values = {"a", "B", "c", "d", "e "};
IterationSample collection = new IterationSample (values, 3 );
Foreach (object x in collection)
{Www.2cto.com
Console. WriteLine (x );
}

The yield keyword instructs the compiler that its method is an iterator block. The compiler generates a class to implement the behavior represented in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerated object. This is a return value, for example, the value returned in each loop of the foreach statement. The yield keyword can also be used with break to indicate the end of iteration.
[Csharp]
Yield return <expression>;
Yield break;

Iii. iterator
The iterator is a new feature in C #2.0. An iterator is a method, get accessor or operator that enables you to support foreach iteration in a class or structure without implementing the entire IEnumerable interface. You only need to provide an iterator to traverse the data structure in the class. When the compiler detects the iterator, it will automatically generate an iteration method for the IEnumerable or IEnumerable <T> interface, further simplifying iterative development.
[Csharp]
Public class Program
{
// Using System. Collections;
Public static IEnumerable Power (int number, int exponent)
{
Int counter = 0;
Int result = 1;
While (counter ++ <exponent)
{
Result = result * number;
Yield return result;
}
}
 
Static void Main ()
{
// Display powers of 2 up to the exponent 8:
Foreach (int I in Power (2, 8 ))
{
Console. Write ("{0}", I );
}
}
}
/*
Output:
2 4 8 16 32 64 128 256
*/

Iv. Implement LINQ query by iterator
The following example uses the iterator to implement the Where Method in the LINQ query.
[Csharp]
Public static IEnumerable <T> Where <T> (IEnumerable <T> source,
Predicate <T> predicate)
{
If (source = null | predicate = null)
{
Throw new ArgumentNullException ();
}
Return WhereImpl (source, predicate );
}
Private static IEnumerable <T> WhereImpl <T> (IEnumerable <T> source,
Predicate <T> predicate)
{
Foreach (T item in source)
{
If (predicate (item ))
{
Yield return item;
}
}
}
...
IEnumerable <string> lines = LineReader. ReadLines (".../FakeLinq. cs ");
Predicate <string> predicate = delegate (string line)
{Return line. StartsWith ("using ");};
Foreach (string line in Where (lines, predicate ))
{
Console. WriteLine (line );
}

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.