Is yield useful outside of LINQ?

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

    I do understand its usefulness in linq, but I feel that only the linq team is writing such complex queriable objects that yield is useful.

    Yield was useful as soon as it got implemented in .NET 2.0, which was long before anyone ever thought of LINQ.

    Why would I write this function:

    IList LoadStuff() {
      var ret = new List();
      foreach(var x in SomeExternalResource)
        ret.Add(x);
      return ret;
    }
    

    When I can use yield, and save the effort and complexity of creating a temporary list for no good reason:

    IEnumerable LoadStuff() {
      foreach(var x in SomeExternalResource)
        yield return x;
    }
    

    It can also have huge performance advantages. If your code only happens to use the first 5 elements of the collection, then using yield will often avoid the effort of loading anything past that point. If you build a collection then return it, you waste a ton of time and space loading things you'll never need.

    I could go on and on....

提交回复
热议问题