Force Linq to not delay execution

天大地大妈咪最大 提交于 2019-12-03 11:01:21

You wouldn't be boxing anything - you'd be buffering the results.

Using ToList() is basically the way to go if you actually want the data. Unless you're ready to use the data immediately, it's got to be buffered somewhere, hasn't it? A list is just a convenient way to do that.

The alternative is to do the processing then and there as well - use the data as you produce it, eagerly. I didn't quite follow the different threads side of thing, so it's not clear to me whether that would help you, but those are basically the choices available to you as far as I can see.

This is actually somewhat explicit in your description:

The design model up to this point is to send data-gathering threads off to find data, and when they're complete pass the data up for computation.

Calling ToList() basically changes what you return from "a query which can fetch the data when asked to" to "the data itself, buffered in a list".

Can you explain more why .ToList is not acceptable? You mentioned boxing and unboxing but those are completely unrelated topics.

Part of forcing a LINQ query to complete on demand necessitates storing the results. Otherwise in order to see the results again, you'd have to repprocess the query. .ToList efficiently achieves this by storing the elements in a List<T>.

It's possible to store the elements in virtually any other collection style data structure with various trade offs that may suit your needs better.

There is a LoadOptions property in the DataContext class that could help you fetch the data more eagerly.

Else you could use a few clever placed ToList() 's.

I know this thread is old... anyway, funny no-one mentioned .ToLast() yet. I'm doing something where linq is not much more than a glorified foreach driving some side effects where I don't really care about the query result... so I didn't want to allocate any more bogus memory than necessary.

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