1) Why can arrays be traversed by foreach?
Because the array can provide an object called enumerator as needed. This object implements the IEnumerator interface.
At a higher level, all objects traversed by foreach implement the IEnumerable interface, and call the GetEnumerator () Response of the object during the duration. The returned result is an object that implements the IEnumerator interface.
Three enumeration modes: IEnumerable/IEnumerator and IEnumerable <T>/IEnumerator <T>
That is to say, all arrays implement the IEnemerator interface by default, which contains three methods: public object Current {get {return;} public bool MoveNext () {} public void Reset (){}
Example:
Namespace ConsoleTest
{
Class Program
{
Static void Main (string [] args)
{
MyColor colors = new MyColor ();
Foreach (var color in colors)
{
Console. WriteLine (color );
}
Console. Read ();
}
}
Class MyColor: IEnumerable
{
Public IEnumerator GetEnumerator ()
{
String [] Colors = {"Red", "yellow", "Blue "};
Return new ColorEnumerator (Colors );
}
}
Class ColorEnumerator: IEnumerator
{
String [] Colors;
Private int Position =-1;
Public object Current
{
Get {return Colors [Position];}
}
Public bool MoveNext ()
{
If (Position <Colors. Length-1)
{
Position ++;
Return true;
}
Return false;
}
Public void Reset ()
{
Position =-1;
}
Public ColorEnumerator (string [] theColors)
{
Colors = new string [theColors. Length];
For (int I = 0; I <theColors. Length; I ++)
{
Colors [I] = theColors [I];
}
}
}
}
2) query by using linq to SQL
Var q = from c in dbContext. MERs
Where c. City = "shenzhen"
Select c;
The result is of the IQuerable type, and is obtained from the database every time you foreach. The advantage of remote query is that you can use the database index without getting unnecessary data. Applicable scenario: foreach is once, so you only need to check the database once.
While the query by using linq to object
Var q = (from c in dbContext. MERs
Where c. City = "shenzhen"
Select c). AsEnumerable ();
The result is of the IEnemerable <T> type. The data is stored in the local memory every time you foreach the data. Applicable scenarios: Multiple foreach times.
All the preceding foreach functions can be replaced with count (), sum (), and other Aggregate functions. When these functions are executed, the data source has been queried.