How to add List<B> to Object A, where List<B> is part of class A

。_饼干妹妹 提交于 2021-01-29 09:15:25

问题


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"];
    };
}

回答1:


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

How to use DataReader




回答2:


As was mentioned in the comments, you'll need to keep track of which customers you have already seen by putting them into a dictionary using the CustomerId as a key. Here's the basic approach:

For each record you read, first get the CustomerId from the reader and check whether that customer is already in the dictionary. If it is, then get that customer object from the dictionary; otherwise, create a new customer from the reader and add it to the dictionary. Then, get the product data from the reader, create a new product and add the product to the customer's list of products.

Here is what it might look like in code:

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

Then, you can dump out the data like this:

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

Fiddle: https://dotnetfiddle.net/iO9vdM



来源:https://stackoverflow.com/questions/60958355/how-to-add-listb-to-object-a-where-listb-is-part-of-class-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!