I had following Service method –
public static DataTable GetBookDetails(BookEntities context)
{
DataTable dtBooks= new DataTable();
dtBooks.TableName = "BookDetails";
dtBooks.Columns.Add(new DataColumn("Name",typeof(string)));
dtBooks.Columns.Add(new DataColumn("ISBN",typeof(string)));
dtBooks.Columns.Add(new DataColumn("Price",typeof(int)));
dtBooks.Columns.Add(new DataColumn("Author",typeof(string)));
IQueryable<Book> query = from b in context.Books.Include("Authors")
.Include("Details/Price")
.Include("Activity")
where b.Activity.IsActive
select b;
if (query != null)
{
var sorted = query.ToArray().OrderByDescending(b => b.Activity.DateCreated);
foreach (Book bb in sorted)
{
DataRow row = dtBooks.NewRow();
row["Name"] = bb.Name;
row["ISBN"] = bb.ISBN;
row["Price"] = bb.Details.Price.CostOfBook;
row["Author"] = bb.Authors.Name;
dtBooks.Rows.Add(row);
}
}
else
dtBooks= null;
return dtBooks;
}
My Questions are –
- Is this an efficient way to get details or can I improve this method?
- Someone suggested me to use IList instead of DataTable. Should I use this? If so, what are the advantages?
- What’s wrong in using DataTable?
DataTable vs IList
IListrepresent collection that can be accessed by index. Nothing more.DataTablealso has similar capabilities, but it provides much more functionality (like more events, More features) and is suitable where these features are required like representing Tabular data with advance capabilities (binding, custom sorting, grouping, event for row changed, cell added etc). All these extra features comes at extra overhead (of more memory requirement).You can slightly improve by using
IList. The improvement is not in faster data access, but in not using extra features thatDataTableprovides.If you dont require access by index, you can further improve by usingIEnumerable.You can further improve upon by using generics version.
IList<T>, orIEnumerable<T>to save upon boxing/unboxing overhead.IList does not have overhead of plethora of features provided by
DataTableother than access by index.Nothing wrong.
DataTableis more suitable where advanced data access features are required.