这里是我的查询结果和类,我想要列表如何创建“客户”列表对象列表“合同”是属性
customer contract_id number_of_products
1 HD2 1000
1 HD3 4500
1 HD4 20000
2 HD5 70
2 HD6 8000
3 HD7 660
3 HD8 2200
public class customer
{
public string customer { get; set; }
public List<contract> ls_contract{ get; set; }
}
public class contract
{
public string contract_id{ get; set; }
public string number_of_products { get; set; }
}
答案 0 :(得分:2)
首先,您需要遵循C#编码惯例:
public class Customer
{
public string Name { get; set; }
public List<Contract> Contracts { get; set; }
}
public class Contract
{
public string Id { get; set; }
public string NumberOfProducts { get; set; }
}
您需要一些平面数据结构来从。
中读取查询结果private class CustomerContract
{
public string CustomerName { get; set;}
public string ContractId { get; set;}
public int NumberOfProducts { get; set;}
}
将结果集读取到该平面数据结构后,您可以按客户ID分组并转换为所需的数据结构。
var result = customerContract.GroupBy(item => item.CustomerName)
.Select(group => new Customer {
Name = group.CustomerName,
Contracts = group.Select(
e => new Contract {
Id = e.ContractId,
NumberOfProducts = e.NumberOfProducts
}
).ToList()
})
.ToList();
答案 1 :(得分:1)
您可以创建并填充Customer列表,
List<Customer> lstCustomer = new List<Customer>()
{
new Customer(){customer="1", ls_contract=new List<Contract>()
{
new Contract(){contract_id="HD2", number_of_products="1000"},
new Contract(){contract_id="HD3", number_of_products="4500"},
new Contract(){contract_id="HD4", number_of_products="20000"}
} },
new Customer(){customer="2", ls_contract=new List<Contract>()
{
new Contract(){contract_id="HD5", number_of_products="70"},
new Contract(){contract_id="HD6", number_of_products="8000"},
} },
new Customer(){customer="3", ls_contract=new List<Contract>()
{
new Contract(){contract_id="HD7", number_of_products="660"},
new Contract(){contract_id="HD8", number_of_products="2200"},
} }
};