How does LINQ defer execution when in a using statement

后端 未结 2 811
孤城傲影
孤城傲影 2021-02-08 01:36

Imagine I have the following:

private IEnumerable MyFunc(parameter a)
{
   using(MyDataContext dc = new MyDataContext)
   {
      return dc.tablename.Select(row          


        
2条回答
  •  南旧
    南旧 (楼主)
    2021-02-08 02:07

    I just posted another deferred-execution solution to this problem here, including this sample code:

    IQueryable MyFunc(string myValue)
    {
        return from dc in new MyDataContext().Use()
               from row in dc.MyTable
               where row.MyField == myValue
               select row;
    }
    
    void UsingFunc()
    {
        var result = MyFunc("MyValue").OrderBy(row => row.SortOrder);
        foreach(var row in result)
        {
            //Do something
        }
    }
    

    The Use() extension method essentially acts like a deferred using block.

提交回复
热议问题