LINQ 太强了!强大到这样的功能,可以一句话搞定。
Select the top five customers in the Northwind database
whose contact is the owner and those owners who placed orders totaling more than
$10,000, then create XML containing the company name, contact name, phone
number, and total amount of the orders. Finally, the results are written out to the
BigSpenders.xml file:
Code
Northwind dataContext = new Northwind(Settings.Default.NorthwindConnectionString);
// Log the generated SQL to the console
dataContext.Log = Console.Out;
var bigSpenders = new XElement("BigSpenders",
from top5 in
(
from customer in
(
from c in dataContext.Customers
// get the customers where the contact is the owner
// and they placed orders
where c.ContactTitle.Contains("Owner")
&& c.Orders.Count > 0
join orderData in
(
from c in dataContext.Customers
// get the customers where the contact is the owner
// and they placed orders
where c.ContactTitle.Contains("Owner")
&& c.Orders.Count > 0
from o in c.Orders
// get the order details
join od in dataContext.OrderDetails
on o.OrderID equals od.OrderID
select new
{
c.CompanyName,
c.CustomerID,
o.OrderID,
// have to calc order value from orderdetails
//(UnitPrice*Quantity as Total)- (Total*Discount)
// as NetOrderTotal
NetOrderTotal = (
(((double)od.UnitPrice) * od.Quantity) -
((((double)od.UnitPrice) * od.Quantity) * od.
Discount))
}
)
on c.CustomerID equals orderData.CustomerID
into customerOrders
select new
{
c.CompanyName,
c.ContactName,
c.Phone,
// Get the total amount spent by the customer
TotalSpend = customerOrders.Sum(order => order.NetOrderTotal)
}
)
// place focus on the customers that spent > 10000
where customer.TotalSpend > 10000
orderby customer.TotalSpend descending
// only take the top five spenders
select customer).Take(5)
)
// format the data as XML
select new XElement("Customer",
new XAttribute("companyName", top5.CompanyName),
new XAttribute("contactName", top5.ContactName),
new XAttribute("phoneNumber", top5.Phone),
new XAttribute("amountSpent", top5.TotalSpend)));
using (XmlWriter writer = XmlWriter.Create("BigSpenders.xml"))
{
bigSpenders.WriteTo(writer);
}