深入理解 c# 第一章 连接(joining) 过滤(filtering) 排序(ordering) 投影(projecting) c#3

    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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值