As in the accepted answer, you can implement it as an iterator function, but keep in mind that in case orderedItemsResult is an IDisposable such as IDataReader for reading from something like a database (the methods called on it appear that this is the case) to make sure to embed it in a try/finally or using block.
For example:
IEnumerable<OrderItem> GetOrders(string connectionString, string queryString)
{
IDbConnection connection = new MyDbConnection(connectionString);
IDbCommand command = null;
IDbReader orderedItemsResult = null;
try
{
connection.Open();
command = new MyCommand(queryString, connection);
orderedItemsResult = command.ExecuteReader();
while (orderItemsResult.Read())
{
yield return new OrderItem()
{
ItemName = orderItemsResult.GetString("item_name"),
Price = orderItemsResult.GetFloat("price"),
Quantity = orderItemsResult.GetInt32("quantity")
};
}
}
finally
{
orderItemsResult?.Dispose();
command?.Dispose();
connection.Dispose();
}
}
The IEnumerable returned which implements IDisposable as well executes the finally block whenever it is disposed (for example, when a foreach is done with it)