Linq查询将嵌套列表拆分为多个表
本文关键字:拆分 列表 查询 嵌套 Linq | 更新日期: 2023-09-27 18:12:32
我有以下数据结构
List<Items> items = new List<Items>();
items.Add(new Item()
{
P1 = "P1",
P2 = "P2",
P3 = "P3",
P4 = new List<P4>
{
new P4() {T1 = 1, T2 = "test", T3 = 1, T4 = 1},
new P4() {T1 = 2, T2 = "test", T3 = 2, T4 = 2},
}
});
items.Add(new Item()
{
P1 = "P11",
P2 = "P12",
P3 = "P13",
P4 = new List<P4>
{
new P4() {T1 = 3, T2 = "test", T3 = 3, T4 = 1},
new P4() {T1 = 4, T2 = "test", T3 = 3, T4 = 1},
}
});
我有GetData()
方法返回上述数据结构/data。
我有三张表
Table 1 columns are: P1, P2, P3
Table 2 columns are: T1 and T2, (P1 FK)
Table 3 columns are: T3, T4 (T1 FK)
我不知道如何转换/分割我的上述数据结构来存储它进入以上三个表?
我试着
创建一个class.cs
public class DTO
{
public list<table1> table 1 {get; set;}
}
public class table 1
{
public string P1 {get; set;}
public string P2 {get; set;}
public string P3 {get; set;}
public list<tabl2>
}
public class table 2
{
public string t1 {get; set;}
public string t2 {get; set;}
public list<t3>
}
public class table 3
{
public string t3 {get; set;}
public string t4 {get; set;}
}
查询尝试了一些查询,但无法成功
Dto dto = new Dto();
var data = GetData();
foreach(item it in data)
{
dto.table1.add(new table1
{
p1 = it.p1,
p2 = it.p2,
p3 = it.p3
t1 // not sure how i populate this since it is expecting list
})
}
未抛光版本。但是像下面这样:
var tables = new List<Table1>();
foreach (var item in items)
{
var t1 = new Table1
{
P1 = item.P1,
P2 = item.P2,
P3 = item.P3,
Table2s = new List<Table2>()
};
var p4Group = item.P4s.GroupBy(pt => new {pt.T1, pt.T2 });
foreach (var p4 in p4Group)
{
var table2 = new Table2
{
T1 = p4.Key.T1,T2 = p4.Key.T2, Table3s = new List<Table3>()
};
var p4S = p4.ToList();
foreach (var p4FromGroup in p4S)
{
table2.Table3s.Add(new Table3
{
T3 = p4FromGroup.T3,
T4 = p4FromGroup.T4
});
}
t1.Table2s.Add(table2);
}
tables.Add(t1);
}
我不确定我是否完全理解你的模型但我认为有一种方法可以类似于
List<Table1> itemsTable 1 =
items.select(i => new Table1() {
p1 = i.p1,
p2 = i.p2,
p3 = i.p3,
Table2 = i.p4.select(p4 => MapToTable2(p4)).ToList()
}).ToList();
private Table2 MapToTable2(P4 p4Items){
return new Table2() {
t1 = p4.T1,
t2 = p4.T2
Table3 = new Table3() {
t3 = p4.T3,
t4 = p4.T4
}
};
}