我有课程:
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Order> Orders { get; set; }
}
public class Order
{
public string Name { get; set; }
}
我无法修改这些课程。我的方法:
public static void DoSomething(IList<Customer> customers)
获取数据,现在我需要为每个项添加此数据ID(id第一个客户应为=例如10,id第一个订单应为=例如50)。所以: 第一个客户应该有id = 10,该客户的第一个订单应该有id = 50和customerId = 10,该客户的第二个订单应该有id = 51和customerId = 10等
我在下面写了这段代码,但它太可怕了,是更好的方法??:
public class Customer2 : Customer
{
public int Id { get; set; }
public new List<Order2> Orders { get; set; }
}
public class Order2 : Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
}
public static void DoSomething(IList<Customer> customers)
{
var customers2 = new List<Customer2>();
var customerId = 10;
var orderId = 50;
for (int i = 0; i < customers.Count; i++)
{
var currentCustomer = customers[i];
var currentCustomerOrders = currentCustomer.Orders;
var orders2 = new List<Order2>();
for (int i2 = 0; i2 < currentCustomerOrders.Count; i2++)
{
var currentCustomerOrder = currentCustomerOrders[i2];
orders2.Add(new Order2 { Id = orderId, CustomerId = customerId, Name = currentCustomerOrder.Name });
orderId++;
}
customers2.Add(new Customer2 { Id = customerId, FirstName = currentCustomer.FirstName, LastName = currentCustomer.LastName, Orders = orders2 });
customerId++;
}
}
答案 0 :(得分:1)
首先,它看起来你正确的轨道,除了重复列表,@ Marc在评论中注明。
以下是需要考虑的一些要点。