Loading class as a list
I have a class
public class Orders
{
public Orders() {}
private st开发者_如何转开发ring _idOrder;
private string _totalPrice;
public string idOrder
{
get{ return _idOrder;}
set { _idOrder = value;}
}
public string totalPrice
{
get { return _totalPrice; }
set { _totalPrice = value; }
}
}
I am loading the list from database like this
while (dr.Read())
{
Orders.idOrder = dr["IdOrder"].ToString();
Orders.totalPrice= dr["totalPrice"].ToString();
}
It's is showing me only last record. How can I load all the orders and retrieve them back by foreach loop?
Create a list :-)
List<Order> orders = new List<Order>();
while (dr.Read())
{
Order order = new Order();
order.idOrder = dr["IdOrder"].ToString();
order.totalPrice= dr["totalPrice"].ToString();
orders.Add(order);
}
As you see, I renamed your class from Orders
to Order
, because that's what it really represents: One order. To have more orders, you need to put those single orders into a list.
It's only showing you the one item, because you're only changing properties on the one item, not instantiating a new one:
var results = new List<Order>();
while (reader.Read())
{
var order = new Order
{
Id = (int)reader["IdOrder"],
TotalPrice = (decimal)reader["totalPrice"]
};
results.Add(order);
}
I think you are looking for something like this:
IEnumberable<Order> FetchOrders()
{
while(dr.Read())
yield return new Order {
idOrder=dr["IdOrder"].ToString(),
totalPrice=dr["totalPrice"].ToString()
});
}
That Orders
class represents a single order! If what you need is a list of orders then I suggest you rename that class to Order, and then create a List<Order>
(a list of order-objects) and populate that from your query results.
Also (forgive me for being pernickety) "idOrder" is not a good field name. The standard approaches are "orderId" or just plain old "Id" (ID, or even id). Likewise I would expect the price-of-ONE-order to be called just "amount", or even "price"... not "totalPrice"... it'll be too confusing when you come to total-up the totalPrices... get my drift?
Cheers. Keith.
I don't see how that will compile. Orders.idOrder is not a static property, it's an instance property.
If i understand you right you want to use something like this:
List<Order> = new List<Order>();
while (dr.Read())
{
Order newOrder = new Order();
newOrder.idOrder = dr["IdOrder"].ToString();
newOrder.totalPrice= dr["totalPrice"].ToString();
orderList.Add(newOrder);
}
Notice this that I just discuss more for @Grook Answer. I Think it is so near to what to want.
IEnumberable<Order> FetchOrders()
{
while(dr.Read())
yield return new Order {
idOrder=dr["IdOrder"].ToString(),
totalPrice=dr["totalPrice"].ToString()
});
}
Then You can easily use foreach loop
Foreach(Order order in GetOrders())
{
doSomething(order);
}
Is it clear?
精彩评论