Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you ToList()?

Tags:

Do you have a default type that you prefer to use in your dealings with the results of LINQ queries?

By default LINQ will return an IEnumerable<> or maybe an IOrderedEnumerable<>. We have found that a List<> is generally more useful to us, so have adopted a habit of ToList()ing our queries most of the time, and certainly using List<> in our function arguments and return values.

The only exception to this has been in LINQ to SQL where calling .ToList() would enumerate the IEnumerable prematurely.

We are also using WCF extensively, the default collection type of which is System.Array. We always change this to System.Collections.Generic.List in the Service Reference Settings dialog in VS2008 for consistency with the rest of our codebase.

What do you do?

like image 529
Richard Ev Avatar asked Dec 02 '08 16:12

Richard Ev


1 Answers

ToList always evaluates the sequence immediately - not just in LINQ to SQL. If you want that, that's fine - but it's not always appropriate.

Personally I would try to avoid declaring that you return List<T> directly - usually IList<T> is more appropriate, and allows you to change to a different implementation later on. Of course, there are some operations which are only specified on List<T> itself... this sort of decision is always tricky.

EDIT: (I would have put this in a comment, but it would be too bulky.) Deferred execution allows you to deal with data sources which are too big to fit in memory. For instance, if you're processing log files - transforming them from one format to another, uploading them into a database, working out some stats, or something like that - you may very well be able to handle arbitrary amounts of data by streaming it, but you really don't want to suck everything into memory. This may not be a concern for your particular application, but it's something to bear in mind.

like image 135
Jon Skeet Avatar answered Nov 22 '22 08:11

Jon Skeet