I have an class Item that represents an item in a list. I have in it function that calls stored procedure that returns datatable and I need to convert the datatable to Array of items.
Here is what I do:
public class Item
{
private string _ItemIdDataName = "item_id";
private string _ItemNameDataName = "item_name";
private string _PriceDataName = "price";
public long ItemId { get; set; }
public string ItemName { get; set; }
public float Price { get; set; }
private Item(DataRow row)
{
if (row != null)
{
ItemId = long.Parse(row[_ItemIdDataName].ToString());
ItemName = row[_ItemNameDataName].ToString();
Price = float.Parse(row[_PriceDataName].ToString());
}
}
public Item[] load()
{
DataTable dt=DBHandler.GetItems();//Stored procedure that returns DataTable
Item[] items = new Item[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
items[i] = new Item(dt.Rows[i]);
}
return items;
}
}
Am I doing it right?
How can I improve this?
If you’re only gonna use it once it probably fine, but if you’ll do it a lot you should try to do some more generic stuff. I wrote a blog post about how to write an extension method for
DataTablethat creates a list of objects. It works by the convention that the properties in the object should have the same name as the columns in the stored procedure (I would change the name in the stored procedure if I could):Now you can just call
or
The blog post is here: http://blog.tomasjansson.com/2010/11/convert-datatable-to-generic-list-extension
There are many ways in which you can extend this, you could include some kind of mapping dictionary telling the extension how to map the columns, in that way the names doesn’t need to match. Or you can add a list of property names that you would like to exclude in the mapping.
Update: Your object (
Item) you are creating must have a default constructor otherwise the private method won’t be able to create it. Since the way the solution works is first to create the object than use the properties that you get from the reflection to set the values of the object.Update 2: I added the part with mappings dictionary but haven’t tried it myself so it might not compile. However, the concept is there and I think it works.