yield return in C#

Yield has two great uses

  1. It helps to provide custom iteration with out creating temp collections.

  2. 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"));
    }
}

  

 

  1. It helps to provide custom iteration with out creating temp collections.
  2. It helps to do stateful iteration.

  3. In order to explain the above two points more demonstratively, I have created a simple video and the link for same is here: http://www.youtube.com/watch?v=4fju3xcm21M
posted @ 2015-12-14 10:10  Jeremy Wu  阅读(162)  评论(0编辑  收藏  举报