Linq Should I return a list <T> Or IEnumerable <T> when I can do more later
I have some methods that return a List of T, for example, say GetAllEvents. In some cases, I then need to filter this list of events (or any of my other list) by date or other property of the elements.
I know that LINQ queries can be βchainedβ or have the number of lines that completes them, and the query will not be executed until you actually need to use them in a non-linq expression (please correct me if I am mistaken in this belief.)
My question is: if my GetAllXXX method returns a list of what I get, is the .ToList () method that I use at the end of my GetAllXXX code that executes LINQ? Should I return IEnumerable? If only for those cases when I need to do something further with the "results" before the query is actually executed.
Here is an example of my concern: I will say 1000 events. GetAllEvents will retrieve all 1000 and give me a list of them. Then, depending on which page the user is on, only events for Today, this week, or a certain category can be displayed. Ideally, by the time I show the user 5 events that are happening today, I really don't want to transfer all 1000 through the wire, and then trim it down to the 5 that they really want. Yes, I know that this is the server side at the moment, but if it still allocates memory for 1000, I try to avoid this.
Any pointers or suggestions?
Eric Lippert , , IQueryable, ( ). LINQ- API , LINQ, . ,
interface IOneTripEnumerable<T> : IEnumerable<T>
LINQ- Where IOneTripEnumerable
IOneTripEnumerable.Where , IOneTripEnumerable . IOneTripEnumerable.GetEnumerator, , .
( : , GetEnumerator , , .)
If you get more time and see the need, you can optimize it by adding additional LINQ methods, but just controlling Where (to allow filtering on the server) and GetEnumerator (to get all the results in a single round-trip tour) can give you good results when low cost to sell. You do not need to implement all of IQueryable. (Note that Count, Any, and Take are also very good candidates for round-robin optimization and trivial to implement).