Yield has two great uses
It helps to provide custom iteration with out creating temp collections.
It helps to do stateful iteration
Iteration. It creates a state machine "under the covers" that remembers where you were on each additional cycle of the function and picks up from there.
e.g.
private static IEnumerable<string> GetIdList(DateTime startTime, DateTime endTime)
{
var collectionList = new List<string>();
for (var dateTime = new DateTime(startTime.Year, startTime.Month, 1); dateTime <= endTime; dateTime = dateTime.AddMonths(1))
{
collectionList.Add(dateTime.ToString("d"));
}
return collectionList;
}
could be writen as:
private static IEnumerable<string> GetIdList(DateTime startTime, DateTime endTime)
{
for (var dateTime = new DateTime(startTime.Year, startTime.Month, 1); dateTime <= endTime; dateTime = dateTime.AddMonths(1))
{
yield return collectionList.Add(dateTime.ToString("d"));
}
}
It helps to do stateful iteration.
原文:http://www.cnblogs.com/wushuaiyi/p/5044293.html