views:

584

answers:

4

I'm having a debate with another programmer I work with.

Are there any significant memory usage or performance differences, or other cons which should make someone avoid using the DataTable and favour lists(of object)... or vice versa

I prefer using the lists because they are more lightweight, strong typing to the object when accessing properties, returning the list as an interface (ICollection, IEnumerable), and using interfaces easily with the object. They do take more time to set up though when manually using the data reader.

+3  A: 

DataTables are definitely much heavier than Lists, both in memory requirements, and in processor time spent creating them / filling them up.
Using a DataReader is considerable faster (although more verbose) than using DataTables (I'm assuming you're using a DataAdapter to fill them).

That said... Unless this is in some place where it really matters, you're probably fine either way, and both methods will be fast enough, so just go with whatever is more comfortable in each case. (Sometimes you want to fill them up with little code, sometimes you want to read them with little code)

I myself tend to only use DataTables when I'm binding to a GridView, or when I need more than one resultset active at the same time.

Daniel Magliola
+1  A: 

Using DataTables directly means tying yourself to the underlying data source and how it is laid out. This is not good from a maintainability point of view. If all your view needs is a list of some objects, that's all you should be giving it.

Jamie Penney
+1  A: 

Another advantage to using the System.Collections classes is that you get better sorting and searching options. I don't know of any reasonable way to alter the way a DataTable sorts or searches; with the collection classes you just have your class implement IComparable or IEquatable and you can completely customize how List.Sort and List.Contains work.

Also with lists you don't have to worry about DBNull, which has tripped me up on more than one occasion because I was expecting null and got DBNull.

John M Gant
+1  A: 

I also like the fact with IEnumerable(Of T) that you can enhance the underlying type of the collection with methods and properties which makes implementation far more elegant, and the code more maintainable. For example the FullName property. An you can add extension methods to the class if it is out of your control.

    public class IdtUser : IIdtUser
{
    public Guid UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    ...
    public string FullName { get { return String.Format("{0} {1}", FirstName, LastName); } }
}
CRice