Does “foreach” cause repeated Linq execution?

前端 未结 8 1698
自闭症患者
自闭症患者 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:23

    Sometimes it might be a good idea to "cache" a LINQ query using ToList() or ToArray(), if the query is being accessed multiple times in your code.

    But keep in mind that "caching" it still calls a foreach in turn.

    So the basic rule for me is:

    • if a query is simply used in one foreach (and thats it) - then I don't cache the query
    • if a query is used in a foreach and in some other places in the code - then I cache it in a var using ToList/ToArray

提交回复
热议问题