class Customer
{
public string ID { get; set; }
public string Name { get; set; }
public List<Order> OrderList { get; set; }
}
class Order
{
public string OrderNumber { get; set; }
public List<Item> ItemList { get; set; }
}
class Item
{
public string ItemName { get; set; }
}
static void Main(string[] args)
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("CustID");
dt.Columns.Add("Name");
dt.Columns.Add("OrderNumber");
dt.Columns.Add("ItemName");
dt.Rows.Add("1", "A", "O1", "Item1");
dt.Rows.Add("1", "A", "O1", "Item2");
dt.Rows.Add("1", "A", "O1", "Item3");
dt.Rows.Add("1", "A", "O2", "Item4");
dt.Rows.Add("1", "A", "O2", "Item5");
dt.Rows.Add("1", "A", "O3", "Item1");
dt.Rows.Add("2", "B", "O4", "Item1");
dt.Rows.Add("2", "B", "O4", "Item2");
dt.Rows.Add("2", "B", "O5", "Item3");
dt.AcceptChanges();
List<DataRow> dList = dt.AsEnumerable().ToList();
//This is not working
var qry = dList.GroupBy(x => x["CustID"])
.Select(g => new Customer
{
ID = g.Key.ToString(),
Name = g.First()["Name"].ToString(),
OrderList = g.GroupBy(t=> t["OrderNumber"]).Select(x => new Order
{
OrderNumber = x.First()["OrderNumber"].ToString(),
ItemList = g.GroupBy(u => u["OrderNumber"]).Select(y => new Item { ItemName = y.First()["ItemName"].ToString() }).ToList()
}).ToList()
}).ToList();
}
我正在努力获得像这样的输出
Custtomer.Name="A"
Customer.ID="1"
Customer.OrderList = ListOfOrders with "01", "02", "03"
Customer.OrderList[0].ItemList = ListOfItems with that order Item1, Item2, Item3
Custtomer.Name="B"
Customer.ID="2"
Customer.OrderList = ListOfOrders with "04", "05"
Customer.OrderList[0].ItemList = ListOfItems with that order Item4, Item5
有人可以告诉我,我的qry有什么不对吗?
答案 0 :(得分:5)
是的,您正试图在x
电话中使用Select
,但这超出了范围。此外,您尝试直接使用Name
,但它不是分组键的一部分。最后,您尝试在Select中选择一个订单,而不是一组订单。我想你想要这个:
var qry = dList.GroupBy(x => new { CustID = (string) x["CustID"],
Name = (string) x["Name"] })
.Select(g => new Customer {
ID = g.Key.CustID,
Name = g.Key.Name,
OrderList = g.Select(x => new Order {
// Indentation bad to avoid scrolling!
OrderNumber = (string) x["OrderNumber"] })
.ToList()
})
.ToList();
假设CustID是唯一的(因此您每次都会获得相同的名称),您可以按照CustID进行分组,然后按照Achim的回答将第一个客户作为名称 - 但我个人更喜欢将所有“每个客户“密钥中的数据,因为逻辑上您正在分组的内容。
编辑:要回答已修改的问题,可以填充OrderList
属性,如下所示:
OrderList = g.GroupBy(t=> (string) t["OrderNumber"]).Select(x => new Order
{
OrderNumber = x.Key,
ItemList = x.Select(y => new Item {
ItemName = (string) y["ItemName"]
}).ToList()
}).ToList()
...但说实话,到那时它变得非常混乱。
答案 1 :(得分:1)
var qry = dList.GroupBy(x => x["CustID"]).Select(g => new Customer
{
ID = g.Key.ToString(),
Name = g.First()["Name"],
OrderList=g.Select(o => new List<Order>(new Order{ OrderNumber=o["OrderNumber"]}))
}).ToList();