2014年11月11日 星期二

[C#] yield


Original :
public IEnumerable<int> GetCollection(IEnumerable<int> myNumbers)
        {
            var filteredNumbers = new List<int>();
            foreach (var number in myNumbers)
            {
                if (number > 100)
                    break;
                else
                    filteredNumbers.Add(number);
            }
            return filteredNumbers.AsEnumerable();
        }

Use yield :
public IEnumerable<int> GetCollection(IEnumerable<int> myNumbers)
{
            foreach (var number in myNumbers)
            {
                if (number > 100)
                    yield break;
                else
                    yield return number;

            }
}


沒有留言:

張貼留言