首页 > 解决方案 > 如何将列表添加到对象 A,其中列表是 A 类的一部分

问题描述

标签: c#sqldatareader

解决方案


CustomerId正如评论中提到的,您需要通过使用作为键将它们放入字典来跟踪您已经看到的客户。这是基本方法:

对于您阅读的每条记录,首先CustomerId从阅读器获取并检查该客户是否已经在字典中。如果是,则从字典中获取该客户对象;否则,从阅读器创建一个新客户并将其添加到字典中。然后,从阅读器获取产品数据,创建新产品并将产品添加到客户的产品列表中。

以下是它在代码中的样子:

var customersById = new Dictionary<int, Customer>();

while (reader.Read())
{
    int customerId = (int)reader["CustomerId"];
    Customer customer;
    if (!customersById.TryGetValue(customerId, out customer))
    {
        customer = new Customer
        {
            CustomerId = customerId,
            Name = (string)reader["CustomerName"],
            City = (string)reader["City"],
            Products = new List<Product>()
        };
        customersById.Add(customerId, customer);
    }
    Product product = new Product
    {
        CustomerId = customerId,
        ProductId = (int)reader["ProductId"],
        Name = (string)reader["ProductName"],
        Quantity = (int)reader["Quantity"]
    };
    customer.Products.Add(product);
}

然后,您可以像这样转储数据:

Console.WriteLine("Product list by customer:\n");
foreach (Customer cust in customersById.Values)
{
    Console.WriteLine(string.Format("{0}) {1} of {2}", cust.CustomerId, cust.Name, cust.City));
    foreach (Product prod in cust.Products)
    {
        Console.WriteLine(string.Format("\t{0}) {1} (qty {2})", prod.ProductId, prod.Name, prod.Quantity));
    }
    Console.Writeline();
}

小提琴:https ://dotnetfiddle.net/iO9vdM


推荐阅读