如何添加列表<B>到对象A,其中List<B>是 A 类的一部分 [英] How to add List<B> to Object A, where List<B> is part of class A
本文介绍了如何添加列表<B>到对象A,其中List<B>是 A 类的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两类客户和产品,如下所示.我正在从数据库获取数据并将其读入 SqlDataReader.从那我必须将它读到客户对象.我们将为每个客户提供多种产品.在这里,我必须将 Product 对象添加到 Customer Object(我们可能为每个客户提供多个产品.请提供任何建议......这样做的最佳方法是什么?
I have two classes of Customer and Products like below. I am getting data from DataBase and reading it into SqlDataReader. From that I have to read it to Customer Object. we will have multiple Products for each Customer. Here I have to add Product object to Customer Object(we may have multiple products for each customer. Any suggestions please.. what is the best way to do this?
public class Customer
{
public int CustomerId {get;set;}
public string Name {get;set;}
public List<Products> _products {get;set;}
}
public class Products
{
public int CustomerId {get;set;}
public int ProductId {get;set;}
public string Name {get;set;}
public int Quantity {get;set;}
}
While(dataReader.Read())
{
var _customer = new Customer{
CustomerId = (int)rdr["CustomerId"];
Name = (string)rdr["CustomerName"];
City = (string)rdr["City"];
};
var _product = new Products
{
CustomerId = (int)rdr["CustomerId"];
ProductId = (int)rdr["ProductId"];
Name = (string)rdr["ProductName"];
Quantity = (int)["Quantity"];
};
}
推荐答案
public List<Customer> GetCustomers(SqlConnection conn) {
using (conn);
conn.Open();
SqlCommand command = new SqlCommand("your_query;",conn);
// your query must return in order
// customerId, customerName, city, productId, productName, quantity
SqlDataReader reader = command.ExecuteReader();
var customers = new List<Customer>();
var products = new List<Product>();
while (reader.Read()) {
var customerId = reader.GetInt32(0);
var customer = new Customer() {
CustomerId = customerId,
Name = reader.GetString(1),
City = reader.GetString(2)
};
var existing = customers.Where(x => x.CustomerId == customerId).FirstOrDefault();
if (existing == null) {
customers.Add(customer);
}
var product = new Products
{
CustomerId = customerId,
ProductId = reader.GetInt32(3),
Name = reader.GetString(4),
Quantity = reader.GetInt32(5)
};
products.Add(product);
}
reader.Close();
return customers.ForEach(item => {
item.Products = products.Where(x => x.customerId == item.CustomerId).ToList();
});
}
}
这篇关于如何添加列表<B>到对象A,其中List<B>是 A 类的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文