//C#的例子
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace linq_part7_csharp
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
NorthwindDataContext db = new NorthwindDataContext();
//var q = from p in db.Products
// select new
// {
// Name = db.MyUpperFunction(p.ProductName)
// };
//GridView1.DataSource = q;
//GridView1.DataBind();
XElement xml = new XElement("Products",
from c in db.Products
orderby c.ProductName
select new XElement("Produ",
new XAttribute("id", c.ProductID),
new XElement("产品名称", c.ProductName),
new XElement("价格", c.UnitPrice))
);
xml.Save(@"C:\xml.xml");
System.Diagnostics.Process.Start(@"C:\xml.xml");
// Loading from a file, you can also load from a stream
//XDocument loaded = XDocument.Load(@"C:\xml.xml");
//var q = from c in loaded.Descendants("contact")
// where (int)c.Attribute("contactId") < 4
// select (string)c.Element("firstName") + "" +
// (string)c.Element("lastName");
// foreach (string name in q)
// Console.WriteLine("Customer name = {0}", name);
}
}
}
//vb的例子,感觉更清晰和直观
Module Module1
Sub Main()
Dim db As New NorthwindDataContext
'Dim customers = <customers>
' <%= From customer In db.Customers _
' Select <customer>
' <name><%= customer.CompanyName %></name>
' <phone><%= customer.Phone %></phone>
' <country><%= customer.Country %></country>
' </customer> %>
' </customers>
'Dim customers = <html>
' <body>
' <table width="100%" border="0">
' <tr>
' <td><b>Name</b></td>
' <td><b>Phone</b></td>
' <td><b>Country</b></td>
' </tr>
' <%= From customer In db.Customers _
' Select <tr>
' <td><%= customer.CompanyName %></td>
' <td><%= customer.Phone %></td>
' <td><%= customer.Country %></td>
' </tr> %>
' </table>
' </body>
' </html>
'customers.Save("c:\customers.html")
'Process.Start("C:\customers.html")
Dim orders = <orders>
<%= From customer In db.Customers _
Select <customer>
<name><%= customer.CompanyName %></name>
<phone><%= customer.Phone %></phone>
<orders>
<%= From order In customer.Orders _
Select <order total=<%= Aggregate detail In order.Order_Details Into Sum(detail.UnitPrice * detail.Quantity) %>>
<date><%= order.OrderDate %></date>
<address><%= order.ShipAddress %></address>
<details>
<%= From detail In order.Order_Details _
Select <item id=<%= detail.ProductID %>>
<product><%= detail.Product.ProductName %></product>
</item> %>
</details>
</order> %>
</orders>
</customer> %>
</orders>
orders.Save("C:\orders.xml")
Process.Start("C:\orders.xml")
End Sub
End Module