Does “foreach” cause repeated Linq execution?

前端 未结 8 1697
自闭症患者
自闭症患者 2020-11-30 08:25

I\'ve been working for the first time with the Entity Framework in .NET, and have been writing LINQ queries in order to get information from my model. I would like to progr

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 09:07

    try this on LinqPad

    void Main()
    {
        var testList = Enumerable.Range(1,10);
        var query = testList.Where(x => 
        {
            Console.WriteLine(string.Format("Doing where on {0}", x));
            return x % 2 == 0;
        });
        Console.WriteLine("First foreach starting");
        foreach(var i in query)
        {
            Console.WriteLine(string.Format("Foreached where on {0}", i));
        }
    
        Console.WriteLine("First foreach ending");
        Console.WriteLine("Second foreach starting");
        foreach(var i in query)
        {
            Console.WriteLine(string.Format("Foreached where on {0} for the second time.", i));
        }
        Console.WriteLine("Second foreach ending");
    }
    

    Each time the where delegate is being run we shall see a console output, hence we can see the Linq query being run each time. Now by looking at the console output we see the second foreach loop still causes the "Doing where on" to print, thus showing that the second usage of foreach does in fact cause the where clause to run again...potentially causing a slow down.

    First foreach starting
    Doing where on 1
    Doing where on 2
    Foreached where on 2
    Doing where on 3
    Doing where on 4
    Foreached where on 4
    Doing where on 5
    Doing where on 6
    Foreached where on 6
    Doing where on 7
    Doing where on 8
    Foreached where on 8
    Doing where on 9
    Doing where on 10
    Foreached where on 10
    First foreach ending
    Second foreach starting
    Doing where on 1
    Doing where on 2
    Foreached where on 2 for the second time.
    Doing where on 3
    Doing where on 4
    Foreached where on 4 for the second time.
    Doing where on 5
    Doing where on 6
    Foreached where on 6 for the second time.
    Doing where on 7
    Doing where on 8
    Foreached where on 8 for the second time.
    Doing where on 9
    Doing where on 10
    Foreached where on 10 for the second time.
    Second foreach ending
    

提交回复
热议问题