Как добавить список <B>в объект A, где список <B>является частью класса A - PullRequest
0 голосов
/ 31 марта 2020

У меня есть два класса клиентов и продуктов, как показано ниже. Я получаю данные из базы данных и считываю их в SqlDataReader. Из этого я должен прочитать это на объекте клиента. у нас будет несколько продуктов для каждого клиента. Здесь я должен добавить объект Product в Customer Object (у нас может быть несколько продуктов для каждого клиента. Любые предложения, пожалуйста. Каков наилучший способ сделать это?

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

Ответы [ 2 ]

1 голос
/ 31 марта 2020

Как уже упоминалось в комментариях, вам нужно отслеживать, каких клиентов вы уже видели, помещая их в словарь, используя CustomerId в качестве ключа. Вот базовый c подход:

Для каждой прочитанной записи сначала получите CustomerId из считывателя и проверьте, есть ли этот клиент уже в словаре. Если это так, то получите этот объект customer из словаря; в противном случае создайте нового читателя из читателя и добавьте его в словарь. Затем получите данные о продукте от читателя, создайте новый продукт и добавьте продукт в список продуктов клиента.

Вот как это может выглядеть в коде:

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

Fiddle: https://dotnetfiddle.net/iO9vdM

0 голосов
/ 31 марта 2020
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();
    });
  }
}

Как использовать DataReader

...