Search code examples
c#object-initializers

Loop through Object Initializer


How can I optimize the following piece of code?

IList<OrderItem> OrderItemsList = new List<OrderItem>();
while (orderItemsResult.Read())
{
    new OrderItem()
    {
        ItemName = orderItemsResult.GetString("item_name"),
        Price = orderItemsResult.GetFloat("price"),
        Quantity = orderItemsResult.GetInt32("quantity")
    },
}

Solution

  • Although a bit late to reply ,still I shall add my thoughts. We can do without List<OrderItem> object. The below code returns IEnumerable<OrderItem>

    while (orderItemsResult.Read())
    {
       yield return new OrderItem()
       {
            ItemName = orderItemsResult.GetString("item_name"),
            Price = orderItemsResult.GetFloat("price"),
            Quantity = orderItemsResult.GetInt32("quantity")
        };
    }