Exemplo n.º 1
0
        static void PLinqExceptions(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var parallel = storage.Products.AsParallel().Select(p =>
            {
                if (p.ProductName.StartsWith("P"))
                {
                    throw new Exception("Problem with product: " + p.ProductName);
                }

                return(new { p.ProductId, p.ProductName, Thread.CurrentThread.ManagedThreadId });
            });

            try
            {
                foreach (var p in parallel)
                {
                    Console.WriteLine("Id = {0}, Product = {1}, ThreadId = {2}", p.ProductId, p.ProductName, p.ManagedThreadId);
                }
            }
            catch (AggregateException aggrex)
            {
                aggrex.Handle(ex =>
                {
                    Console.WriteLine(ex.Message);
                    return(true);
                });
            }
        }
Exemplo n.º 2
0
        static void LinqFirstOrDefaultCondition(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var product789 = storage.Products.FirstOrDefault(p => p.ProductId == 789);

            Console.WriteLine("Product 789 exists: {0}", product789 != null);
        }
Exemplo n.º 3
0
        static void LinqLastSimple(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var product12 = (
                from p in storage.Products
                where p.ProductId == 12
                select p).Last();

            ObjectDumper.Write(product12);
        }
Exemplo n.º 4
0
        static void LinqMaxElements(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var categories =
                from p in storage.Products
                group p by p.Category into g
                let maxPrice = g.Max(p => p.UnitPrice)
                               select new { Category = g.Key, MostExpensiveProducts = g.Where(p => p.UnitPrice == maxPrice) };

            ObjectDumper.Write(categories, 1);
        }
Exemplo n.º 5
0
        static void LinqCountNested(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var orderCounts =
                from c in storage.Customers
                select new { c.CustomerId, OrderCount = c.Orders.Count() };

            // Fluent expression equivalent.
            // var orderCounts = storage.Customers.Select(c => new { c.CustomerId, OrderCount = c.Orders.Count() });

            ObjectDumper.Write(orderCounts);
        }
Exemplo n.º 6
0
        static void PLinqWithDegreeOfParallelism(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var parallel =
                from p in storage.Products.AsParallel().WithDegreeOfParallelism(Environment.ProcessorCount)
                select new { p.ProductId, p.ProductName, Thread.CurrentThread.ManagedThreadId };

            foreach (var p in parallel)
            {
                Console.WriteLine("Id = {0}, Product = {1}, ThreadId = {2}", p.ProductId, p.ProductName, p.ManagedThreadId);
            }
        }
Exemplo n.º 7
0
        static void PLinqAsUnordered(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var parallel =
                from p in storage.Products.AsParallel().AsOrdered().Take(10).AsUnordered()
                select new { p.ProductId, p.ProductName, Thread.CurrentThread.ManagedThreadId };

            foreach (var p in parallel)
            {
                Console.WriteLine("Id = {0}, Product = {1}, ThreadId = {2}", p.ProductId, p.ProductName, p.ManagedThreadId);
            }
        }
Exemplo n.º 8
0
        static void PLinqWithExecutionMode(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var parallel =
                from p in storage.Products.AsParallel().WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                select new { p.ProductId, p.ProductName, Thread.CurrentThread.ManagedThreadId };

            foreach (var p in parallel)
            {
                Console.WriteLine("Id = {0}, Product = {1}, ThreadId = {2}", p.ProductId, p.ProductName, p.ManagedThreadId);
            }
        }
Exemplo n.º 9
0
        static void LinqCountGrouped(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var categoryCounts =
                from p in storage.Products
                group p by p.Category into g
                select new { Category = g.Key, ProductCount = g.Count() };

            // Fluent expression equivalent.
            // var categoryCounts = storage.Products.GroupBy(p => p.Category, (k, g) => new { Category = k, ProductCount = g.Count() });

            ObjectDumper.Write(categoryCounts);
        }
        static void LinqGroupBySimple3(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var orderGroups =
                from p in storage.Products
                group p by p.Category into g
                select new { Category = g.Key, Products = g };

            // Fluent expression equivalent.
            // var orderGroups = storage.Products.GroupBy(p => p.Category, (k, g) => new { Category = k, Products = g });

            ObjectDumper.Write(orderGroups, 1);
        }
Exemplo n.º 11
0
        static void LinqThenByDescendingSimple(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var sortedProducts =
                from prod in storage.Products
                orderby prod.Category, prod.UnitPrice descending
            select prod;

            // Fluent expression equivalent.
            // var sortedProducts = storage.Products.OrderBy(prod => prod.Category).ThenByDescending(prod => prod.UnitPrice);

            ObjectDumper.Write(sortedProducts);
        }
Exemplo n.º 12
0
        static void LinqOrderBySimple3(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var sortedProducts =
                from prod in storage.Products
                orderby prod.ProductName
                select prod;

            // Fluent expression equivalent.
            // var sortedProducts = storage.Products.OrderBy(prod => prod.ProductName);

            ObjectDumper.Write(sortedProducts);
        }
Exemplo n.º 13
0
        static void LinqMaxGrouped(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var categories =
                from p in storage.Products
                group p by p.Category into g
                select new { Category = g.Key, MostExpensivePrice = g.Max(p => p.UnitPrice) };

            // Fluent expression equivalent.
            // var categories = storage.Products.GroupBy(p => p.Category, (k, g) => new { Category = k, MostExpensivePrice = g.Max(p => p.UnitPrice) });

            ObjectDumper.Write(categories);
        }
Exemplo n.º 14
0
        static void LinqSumGrouped(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var categories =
                from p in storage.Products
                group p by p.Category into g
                select new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.UnitsInStock) };

            // Fluent expression equivalent.
            // var categories = storage.Products.GroupBy(p => p.Category, (k, g) => new { Category = k, TotalUnitsInStock = g.Sum(p => p.UnitsInStock) });

            ObjectDumper.Write(categories);
        }
Exemplo n.º 15
0
        static void LinqDistinct2(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var categoryNames = (
                from p in storage.Products
                select p.Category)
                                .Distinct();

            Console.WriteLine("Category names:");
            foreach (var n in categoryNames)
            {
                Console.WriteLine(n);
            }
        }
Exemplo n.º 16
0
        static void LinqAllGrouped(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var productGroups =
                from p in storage.Products
                group p by p.Category into g
                where g.All(p => p.UnitsInStock > 0)
                select new { Category = g.Key, Products = g };

            // Fluent expression equivalent.
            // var productGroups = storage.Products.GroupBy(p => p.Category, (k, g) => new { Category = k, Products = g }).Where(g => g.Products.All(p => p.UnitsInStock > 0));

            ObjectDumper.Write(productGroups, 1);
        }
Exemplo n.º 17
0
        static void LinqSelectManyIndexed(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            // Fluent expression only.
            var customerOrders = storage.Customers.SelectMany((c, cIndex) => c.Orders.Select(o => "Customer #" + (cIndex + 1) + " has an order with OrderID " + o.OrderId));

            /*
             * var customerOrders = storage.Customers.SelectMany(
             *  (c, cIndex) => c.Orders.Select(o => new { index = cIndex, order = o }),
             *  (c, o) => "Customer #" + (o.index + 1) + " has an order with OrderID " + o.order.OrderId);
             */

            ObjectDumper.Write(customerOrders);
        }
        static void LinqTakeNested(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var first3WaOrders = (
                from c in storage.Customers
                from o in c.Orders
                where c.Region == "WA"
                select new { c.CustomerId, o.OrderId, o.OrderDate }).Take(3);

            Console.WriteLine("First 3 orders in WA:");
            foreach (var order in first3WaOrders)
            {
                ObjectDumper.Write(order);
            }
        }
Exemplo n.º 19
0
        static void LinqSelectAnonymousTypes3(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var productInfos =
                from p in storage.Products
                select new { p.ProductName, p.Category, Price = p.UnitPrice };

            // Fluent expression equivalent.
            // var productInfos = storage.Products.Select(p => new { p.ProductName, p.Category, Price = p.UnitPrice });

            Console.WriteLine("Product Info:");
            foreach (var productInfo in productInfos)
            {
                Console.WriteLine("{0} is in the category {1} and costs {2} per unit.", productInfo.ProductName, productInfo.Category, productInfo.Price);
            }
        }
        static void LinqGroupByNested(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var customerOrderGroups =
                from c in storage.Customers
                select
                new
            {
                c.CompanyName,
                YearGroups =
                    from o in c.Orders
                    group o by o.OrderDate.Year into yg
                    select
                    new
                {
                    Year        = yg.Key,
                    MonthGroups =
                        from o in yg
                        group o by o.OrderDate.Month into mg
                        select new { Month = mg.Key, Orders = mg }
                }
            };

            // Fluent expression equivalent.

            /*
             * var customerOrderGroups = storage.Customers.Select(c =>
             *  new
             *  {
             *      c.CompanyName,
             *      YearGroups = c.Orders.GroupBy(
             *          yo => yo.OrderDate.Year,
             *          (yk, yg) =>
             *              new
             *              {
             *                  Year = yk,
             *                  MonthGroups = yg.GroupBy(
             *                      mo => mo.OrderDate.Month,
             *                      (mk, mg) => new { Month = mk, Orders = mg })
             *              })
             *  });
             */

            ObjectDumper.Write(customerOrderGroups, 3);
        }
Exemplo n.º 21
0
        static void LinqSelectSimple2(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var productNames =
                from p in storage.Products
                select p.ProductName;

            // Fluent expression equivalent.
            // var productNames = storage.Products.Select(p => p.ProductName);

            Console.WriteLine("Product Names:");
            foreach (var productName in productNames)
            {
                Console.WriteLine(productName);
            }
        }
        static void LinqSkipNested(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var waOrders =
                from cust in storage.Customers
                from order in cust.Orders
                where cust.Region == "WA"
                select new { cust.CustomerId, order.OrderId, order.OrderDate };

            var allButFirst2Orders = waOrders.Skip(2);

            Console.WriteLine("All but first 2 orders in WA:");
            foreach (var order in allButFirst2Orders)
            {
                ObjectDumper.Write(order);
            }
        }
        static void LinqWhereSimple2(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var soldOutProducts =
                from prod in storage.Products
                where (prod.UnitsInStock == 0)
                select prod;

            // Fluent expression equivalent.
            // var soldOutProducts = storage.Products.Where(prod => prod.UnitsInStock == 0);

            Console.WriteLine("Sold out products:");
            foreach (var product in soldOutProducts)
            {
                Console.WriteLine("{0} is sold out!", product.ProductName);
            }
        }
        static void LinqWhereSimple3(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var expensiveInStockProducts =
                from prod in storage.Products
                where ((prod.UnitsInStock > 0) && (prod.UnitPrice > 3.00M))
                select prod;

            // Fluent expression equivalent.
            // var expensiveInStockProducts = storage.Products.Where(prod => (prod.UnitsInStock > 0) && (prod.UnitPrice > 3.00M));

            Console.WriteLine("In-stock products that cost more than 3.00:");
            foreach (var product in expensiveInStockProducts)
            {
                Console.WriteLine("{0} is in stock and costs more than 3.00.", product.ProductName);
            }
        }
Exemplo n.º 25
0
        static void LinqUnion2(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var productFirstChars =
                from p in storage.Products
                select p.ProductName[0];
            var customerFirstChars =
                from c in storage.Customers
                select c.CompanyName[0];

            var uniqueFirstChars = productFirstChars.Union(customerFirstChars);

            Console.WriteLine("Unique first letters from Product names and Customer names:");
            foreach (var ch in uniqueFirstChars)
            {
                Console.WriteLine(ch);
            }
        }
Exemplo n.º 26
0
        static void LinqConcat2(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var customerNames =
                from c in storage.Customers
                select c.CompanyName;
            var productNames =
                from p in storage.Products
                select p.ProductName;

            var allNames = customerNames.Concat(productNames);

            Console.WriteLine("Customer and product names:");
            foreach (var n in allNames)
            {
                Console.WriteLine(n);
            }
        }
Exemplo n.º 27
0
        static void LinqExcept2(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var productFirstChars =
                from p in storage.Products
                select p.ProductName[0];
            var customerFirstChars =
                from c in storage.Customers
                select c.CompanyName[0];

            var productOnlyFirstChars = productFirstChars.Except(customerFirstChars);

            Console.WriteLine("First letters from Product names, but not from Customer names:");
            foreach (var ch in productOnlyFirstChars)
            {
                Console.WriteLine(ch);
            }
        }
Exemplo n.º 28
0
        static void LinqSelectManyCompoundFrom3(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var orders =
                from c in storage.Customers
                from o in c.Orders
                where o.OrderDate >= new DateTime(1998, 1, 1)
                select new { c.CustomerId, o.OrderId, o.OrderDate };

            // Fluent expression equivalents.
            // var orders = storage.Customers.SelectMany(c => c.Orders.Where(o => o.OrderDate >= new DateTime(1998, 1, 1)).Select(o => new { c.CustomerId, o.OrderId, o.OrderDate }));

            /*
             * var orders = storage.Customers.SelectMany(
             *  c => c.Orders.Where(o => o.OrderDate >= new DateTime(1998, 1, 1)),
             *  (c, o) => new {c.CustomerId, o.OrderId, o.OrderDate});
             */

            ObjectDumper.Write(orders);
        }
        static void LinqWhereDrilldown(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var waCustomers =
                from cust in storage.Customers
                where (cust.Region == "WA")
                select cust;

            // Fluent expression equivalent.
            // var waCustomers = storage.Customers.Where(cust => cust.Region == "WA");

            Console.WriteLine("Customers from Washington and their orders:");
            foreach (var customer in waCustomers)
            {
                Console.WriteLine("Customer {0}: {1}", customer.CustomerId, customer.CompanyName);
                foreach (var order in customer.Orders)
                {
                    Console.WriteLine("  Order {0}: {1}", order.OrderId, order.OrderDate);
                }
            }
        }
Exemplo n.º 30
0
        static void LinqSelectManyFromAssignment(CustomersStorage storage)
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            var orders =
                from c in storage.Customers
                from o in c.Orders
                let total = o.Total
                            where total >= 2000.0M
                            select new { c.CustomerId, o.OrderId, total };

            // Fluent expression equivalents.
            // var orders = storage.Customers.SelectMany(c => c.Orders.Select(o => new { order = o, total = o.Total }).Where(o => o.total < 500.00M).Select(o => new { c.CustomerId, o.order.OrderId, o.total }));

            /*
             * var orders = storage.Customers.SelectMany(
             *  c => c.Orders.Select(o => new { order = o, total = o.Total }).Where(o => o.total < 500.00M),
             *  (c, o) => new { c.CustomerId, o.order.OrderId, o.total });
             */

            ObjectDumper.Write(orders);
        }