class ListJoiningOrderingAndFilteringWithLinq
{
static void Main()
{
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);
}
}
}
LINQ借用了 SQL的语法和一些思路
将产品和 供货商连接起来,通过 id来连接,使用了过滤器,先按供货商名称排序,之后是 产品的名字 最后打印每个匹配的供货商名字和 产品的名字, 如果没有LINQ ,输入更多的代码才能实现
输入1:
public static List<ProductWithSupplierID> GetSampleProducts()
{
return new List<ProductWithSupplierID>
{
new ProductWithSupplierID { Name="West Side Story", Price = 9.99m, SupplierID=1 },
new ProductWithSupplierID { Name="Assassins", Price=14.99m, SupplierID=2 },
new ProductWithSupplierID { Name="Frogs", Price=13.99m, SupplierID=1 },
new ProductWithSupplierID { Name="Sweeney Todd", Price=10.99m, SupplierID=3}
};
}
输入2:
public static List<Supplier> GetSampleSuppliers()
{
return new List<Supplier>
{
new Supplier { Name="Solely Sondheim", SupplierID=1 },
new Supplier { Name="CD-by-CD-by-Sondheim", SupplierID=2 },
new Supplier { Name="Barbershop CDs", SupplierID=3 }
};
}
输出:
Supplier=Barbershop CDs; Product=Sweeney Todd
Supplier=CD-by-CD-by-Sondheim; Product=Assassins
Supplier=Solely Sondheim; Product=Frogs