Why is this LINQ query not executed when using foreach?

爱⌒轻易说出口 提交于 2019-12-01 03:21:20

It's happening because created is a query, not a result. So, every time you enumerate it, you're evaluating the Select over again from scratch.

If you want this to work, make created an actual list, rather than just an IEnumerable representing a query.

For example, add:

created = created.ToList();

You say:

I would expect the foreach-statement to execute the query, and trigger the creation of the objects

This is exactly what is happening. The problem is the creation of the objects happens every time you iterate over created, not just the first time. Since the ElementAt() method iterates over created, it's just creating new As again.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!