Is yield useful outside of LINQ?

后端 未结 14 937
野性不改
野性不改 2020-12-24 06:44

When ever I think I can use the yield keyword, I take a step back and look at how it will impact my project. I always end up returning a collection instead of yeilding becau

14条回答
  •  不思量自难忘°
    2020-12-24 07:29

    The System.Linq IEnumerable extensions are great, but sometime you want more. For example, consider the following extension:

    public static class CollectionSampling
    {
        public static IEnumerable Sample(this IEnumerable coll, int max)
        {
            var rand = new Random();
            using (var enumerator = coll.GetEnumerator());
            {
                while (enumerator.MoveNext())
                {
                    yield return enumerator.Current; 
                    int currentSample = rand.Next(max);
                    for (int i = 1; i <= currentSample; i++)
                        enumerator.MoveNext();
                }
            }
        }    
    }
    

    Another interesting advantage of yielding is that the caller cannot cast the return value to the original collection type and modify your internal collection

提交回复
热议问题