我有以下数据,员工栏目视为父项,每位员工都有子项发票,每张发票都有发票详细信息作为子项。 我已将此数据绑定到类列表中。现在我想使用LINQ
从这个列表中创建层次结构列表parent---> child--->subchild
Employee-Invoice--->InvoiceDetails
List Data:
Employee invoice InvoiceDetails jan feb Mar Apr
E1 I1 ID1 1 2 10 5
E1 I1 ID2 1 3 11 6
E1 I1 ID3 1 4 12 7
E1 I2 ID1 1 5 13 8
E1 I2 ID2 1 6 14 9
E1 I2 ID3 1 7 15 10
E2 I1 ID1 1 8 16 11
E2 I1 ID2 1 10 17 12
Output :
E1
--I1
--ID1 1 2 10 5
--ID2 1 3 11 6
--ID3 1 4 12 7
-I2
--ID1 1 5 13 8
--ID2 1 6 14 9
--ID3 1 7 15 10
E2
--I1
--ID1 1 8 16 11
--ID2 1 10 17 12
如果您需要更多说明,请与我们联系。
答案 0 :(得分:0)
var dataTree = employeeInvoiceDetails.GroupBy(__item => __item.Employee, __item => __item, (__key, __items) => new { Employee = __key, Invoices = __items.GroupBy(___item => ___item.invoice) });
foreach (var employe in dataTree)
{
Console.WriteLine("--{0}", employe.Employee);
foreach (var invoice in employe.Invoices)
{
Console.WriteLine("\t--{0}", invoice.Key);
foreach (var employeeInvoiceDetail in invoice)
Console.WriteLine("\t\t--{0} {1} {2} {3} {4}", employeeInvoiceDetail.InvoiceDetails, employeeInvoiceDetail.jan, employeeInvoiceDetail.feb, employeeInvoiceDetail.Mar, employeeInvoiceDetail.Apr);
}
}
答案 1 :(得分:0)
我认为你的课程看起来像这样:
public class Employee
{
public string Id;
public List<Invoice> Invoices;
}
public class Invoice
{
public string Id;
public List<InvoiceDetails> InvoiceDetails;
}
public class InvoiceDetails
{
public string Id;
}
我认为您的源数据是这样的:
var source = new []
{
new { Employee = "E1", Invoice = "I1", InvoiceDetails = "ID1" },
new { Employee = "E1", Invoice = "I1", InvoiceDetails = "ID2" },
new { Employee = "E1", Invoice = "I1", InvoiceDetails = "ID3" },
new { Employee = "E1", Invoice = "I2", InvoiceDetails = "ID1" },
new { Employee = "E1", Invoice = "I2", InvoiceDetails = "ID2" },
new { Employee = "E1", Invoice = "I2", InvoiceDetails = "ID3" },
new { Employee = "E2", Invoice = "I1", InvoiceDetails = "ID1" },
new { Employee = "E2", Invoice = "I1", InvoiceDetails = "ID2" },
};
然后这是您需要的查询:
var employees =
(
from x in source
group x by x.Employee into gxs
select new Employee()
{
Id = gxs.Key,
Invoices =
(
from y in gxs
group y by y.Invoice into gys
select new Invoice()
{
Id = gys.Key,
InvoiceDetails =
(
from z in gys
select new InvoiceDetails()
{
Id = z.InvoiceDetails,
}
).ToList()
}
).ToList()
}
).ToList();
这给了我这个结果: