遍历对象初始化器

时间:2019-03-16 11:18:32

标签: c# object-initializers

如何优化以下代码?

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

3 个答案:

答案 0 :(得分:2)

虽然回复有点晚,但我还是要加我的想法。 我们可以不使用List<OrderItem>对象。 以下代码返回IEnumerable<OrderItem>

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

答案 1 :(得分:1)

正如@crowcoder和@ er-sho在评论中指出的那样,您需要将OrderItem添加到OrderItemsList

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

    // add to the list
    OrderItemsList.Add(orderItem);
}

答案 2 :(得分:-1)

就像在接受的答案中一样,您可以将其实现为迭代器函数,但是请记住,如果orderedItemsResult是一个IDisposable(例如IDataReader),可以从数据库之类的东西中读取(调用的方法似乎是大小写)以确保将其嵌入try / finally或using块中。 例如:

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();
    }
}

实现IDisposable的IEnumerable返回值也将在处理完后(例如,当完成foreach时)执行finally块