List<ProductWithSupplierID> products = ProductWithSupplierID.GetSampleProducts(); List<Supplier> suppliers = Supplier.GetSampleSuppliers(); var filtered = from p in products join s in suppliers on p.SupplierID equals s.SupplierID where p.Price > 10 orderby s.Name, p.Name select new { SupplierName = s.Name, ProductName = p.Name }; foreach (var v in filtered) { Console.WriteLine("Supplier={0}; Product={1}",v.SupplierName, v.ProductName); }
特性:隐式类型局部变量(implicitly typed local variable)
使用var关键字说明,编译器根据变量的初始值推断其类型
LINQ to XML
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
XDocument doc = XDocument.Load("data.xml"); var filtered = from p in doc.Descendants("Product") join s in doc.Descendants("Supplier") on (int)p.Attribute("SupplierID") equals (int)s.Attribute("SupplierID") where (decimal)p.Attribute("Price") > 10 orderby (string)s.Attribute("Name"), (string)p.Attribute("Name") select new { SupplierName = (string)s.Attribute("Name"), ProductName = (string)p.Attribute("Name") }; foreach (var v in filtered) { Console.WriteLine("Supplier={0}; Product={1}", v.SupplierName, v.ProductName); } }
LINQ to SQL
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
using (LinqDemoDataContext db = new LinqDemoDataContext()) { var filtered = from p in db.Products join s in db.Suppliers on p.SupplierID equals s.SupplierID where p.Price > 10 orderby s.Name, p.Name select new { SupplierName = s.Name, ProductName = p.Name }; foreach (var v in filtered) { Console.WriteLine("Supplier={0}; Product={1}", v.SupplierName, v.ProductName); } }