我有4个XML文件,其中包含此格式的数据。这些数据实际上来自Microsoft Northwind数据库,但我有一些XML格式的表。完整的关系图可用here。
订单
<Orders>
<Order>
<OrderID>10248</OrderID>
<CustomerID>VINET</CustomerID>
<EmployeeID>5</EmployeeID>
</Order>
.............
.............
.............
订单明细
<OrderDetails>
<OrderDetail>
<OrderID>10248</OrderID>
<Quantity>12</Quantity>
<UnitPrice>14.0000</UnitPrice>
</OrderDetail>
<OrderDetail>
<OrderID>10248</OrderID>
<Quantity>10</Quantity>
<UnitPrice>9.8000</UnitPrice>
</OrderDetail>
.............
.............
.............
员工
<Employee>
<EmployeeID>5</EmployeeID>
<FirstName>Steve</FirstName>
<LastName>Buchanan</LastName>
</Employee>
<Employee>
<EmployeeID>6</EmployeeID>
<FirstName>Michael</FirstName>
<LastName>Suyama</LastName>
</Employee>
.............
.............
.............
客户
<Customer>
<CustomerID>VINET</CustomerID>
<CompanyName>Vins et alcools Chevalier</CompanyName>
<ContactName>Paul Henriot</ContactName>
</Customer>
<Customer>
<CustomerID>WANDK</CustomerID>
<CompanyName>Die Wandernde Kuh</CompanyName>
<ContactName>Rita Müller</ContactName>
</Customer>
<Customer>
.............
.............
.............
现在我想得到一个对象列表,以便每个对象包含以下内容:
所以其中一个对象看起来像这样 - {10248,Vins et alcools Chevalier,Paul Henriot,Steve Buchanan,22,266}
现在我可以写一个LINQ查询来获取orderid,contactname和公司名称,如下所示:
var list = from o in ordersList
join cl in customersList
on o.CustomerId equals cl.CustomerId
select new
{
o.OrderId,
cl.CompanyName,
cl.ContactName
};
但这只给了我三件事。我正在努力获得对象所需的所有6件事。还有如何执行计算,因为订单表中的一个orderid可以有多个orderdetails。例如 - 对于订单ID 10248,我们有2个订单详细信息。
由于
答案 0 :(得分:3)
你需要多个联接和分组,如下所示
var list = from o in ordersList
join cl in customersList
on o.CustomerID equals cl.CustomerID
join ol in orderDetailsList
on o.OrderID equals ol.OrderID
join e in employeeList
on o.EmployeeID equals e.EmployeeID
select new
{
o.OrderID,
cl.CompanyName,
cl.ContactName,
EmployeeName = e.FirstName + " " +e.LastName,
ol.Quantity,
ol.UnitPrice
};
var result = list.GroupBy(x => x.OrderID).Select(g => new
{
OrderID = g.Key,
CompanyName = g.First().CompanyName,
ContactName = g.First().ContactName,
EmployeeName = g.First().EmployeeName,
TotalQuantity = g.Sum(x => x.Quantity),
TatalPrice = g.Sum(x => x.Quantity * x.UnitPrice)
});