c# - 如何将列表添加到对象 A,其中列表是 A 类的一部分
问题描述
解决方案
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();
}
推荐阅读
- r - 如何生成而不使用函数combn()在R中重复组合并概括代码?
- c - 调试开始时,将分解点放在变量上,该变量始终显示值为 1
- c++ - 如何在 C/C++ 中使用 OpenSSL 生成 DER 编码的公钥?
- xcode - Cocoapods Pod 包版本检查 - Flutter
- reactjs - React-Bootstrap Modals 导致窗口 EventListener 出现问题
- css - 不访问 ionic5 中的 CSS 类或组件
- cypress - 赛普拉斯不存储全局变量的值?
- javascript - javascript jsPDF库订单元素中的错误
- python - 鼠标和键盘python模块冲突?
- flutter - 在 Dart 中覆盖类字段的最佳实践