Is yield useful outside of LINQ?

后端 未结 14 955
野性不改
野性不改 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:24

    Note that with yield, you are iterating over the collection once, but when you build a list, you'll be iterating over it twice.

    Take, for example, a filter iterator:

    IEnumerator  Filter(this IEnumerator coll, Func func)
    {
         foreach(T t in coll)
            if (func(t))  yield return t;
    }
    

    Now, you can chain this:

     MyColl.Filter(x=> x.id > 100).Filter(x => x.val < 200).Filter (etc)
    

    You method would be creating (and tossing) three lists. My method iterates over it just once.

    Also, when you return a collection, you are forcing a particular implementation on you users. An iterator is more generic.

提交回复
热议问题