Advertisement
Guest User

Untitled

a guest
Jan 16th, 2017
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 28.55 KB | None | 0 0
  1. using System;
  2. using System.Reflection;
  3.  
  4. namespace Linq
  5. {
  6.     public class Program
  7.     {
  8.         public static void Main(string[] args)
  9.         {
  10.             string keuze = "";
  11.             while (keuze != "99")
  12.             {
  13.                 Console.WriteLine("\n\n-------------LINQ Menu--------------");
  14.                 Console.WriteLine("1. Step 1: Extension methods.");
  15.                 Console.WriteLine("2. Step 2: Enkele eenvoudige Linq operatoren.");
  16.                 Console.WriteLine("3. Step 3: Where en lambda expressies");
  17.                 Console.WriteLine("4. Step 4: Select en var/anonieme types");
  18.                 Console.WriteLine("5. Step 5: Nog meer handige LINQ operatoren");
  19.                 Console.WriteLine("6. Oefeningen");
  20.                 Console.WriteLine("99. Exit.");
  21.                 Console.Write("Enter your choice : ");
  22.                 keuze = Console.ReadLine();
  23.                 if (keuze != "99")
  24.                 {
  25.                     Type type = Type.GetType("Linq.Step" + keuze);
  26.                     if (type != null)
  27.                     {
  28.                         Object o = Activator.CreateInstance(type);
  29.                         type.GetMethod("Execute").Invoke(o, null);
  30.                     }
  31.                 }
  32.             }
  33.  
  34.         }
  35.     }
  36. }
  37.  
  38.  
  39. namespace Linq.Models
  40. {
  41.  
  42.     public class CityDistance
  43.     {
  44.         public string Country { get; set; }
  45.         public string Name { get; set; }
  46.         public int DistanceInKm { get; set; }
  47.  
  48.         public override string ToString()
  49.         {
  50.             return $"{Name} in {Country} at {DistanceInKm} km distance";
  51.         }
  52.     }
  53. }
  54.  
  55.  
  56. using System;
  57. using System.Collections.Generic;
  58. using Linq.Models;
  59.  
  60. namespace Extensions
  61. {
  62.     public static class StringExtension
  63.     {
  64.         // voorbeeld: extension method gedefinieerd op string
  65.         public static string RepeatText(this string s, int aantal)
  66.         {
  67.             string resultaat = string.Empty;
  68.             for (int i = 0; i < aantal; i++)
  69.                 resultaat += s;
  70.             return resultaat;
  71.         }
  72.  
  73.         // voorbeeld: extension method gedefinieerd op IEnumerable<Location>
  74.         public static IEnumerable<Location> CheckIfTrue(this IEnumerable<Location> locations, Func<Location, bool> method)
  75.         {
  76.             IList<Location> list = new List<Location>();
  77.             foreach (Location l in locations)
  78.                 if (method(l))
  79.                     list.Add(l);
  80.             return list;
  81.         }
  82.     }
  83.     public static class IntExtension
  84.     {
  85.         // voorbeeld: extension method gedefinieerd op Int32
  86.         public static bool IsEven(this int i)
  87.         {
  88.             return i % 2 == 0;
  89.         }
  90.  
  91.         // voorbeeld: extension method gedefinieerd op IEnumerable<int>
  92.         public static int CalculateSum(this IEnumerable<int> numbers)
  93.         {
  94.             if (numbers == null)
  95.                 throw new ArgumentException();
  96.             int aux = 0;
  97.             foreach (int i in numbers)
  98.                 aux += i;
  99.             return aux;
  100.         }
  101.  
  102.         // maak van IsdivisibleBy een extension method gedefinieerd op een geheel getal
  103.         // de extension method retourneert true wanneer het getal
  104.         // deelbaar is door een ander geheel getal (parameter!)
  105.         public static bool IsDivisibleBy(this int i, int by)
  106.         {
  107.             return i % by == 0;
  108.         }
  109.     }
  110. }
  111.  
  112.  
  113.  
  114. namespace Linq.Models
  115. {
  116.  
  117.     public class Location
  118.     {
  119.         public string Country { get; set; }
  120.         public string City { get; set; }
  121.         public int Distance { get; set; }
  122.         public override string ToString()
  123.         {
  124.             return $"{City} in {Country} at {Distance} miles distance";
  125.         }
  126.     }
  127. }
  128.  
  129.  
  130.  
  131. using System.Collections.Generic;
  132.  
  133. namespace Linq.Models
  134. {
  135.     public class TravelOrganizer
  136.     {
  137.         // list of places visited and their distance to Seattle
  138.         public static IEnumerable<Location> PlacesVisited
  139.         {
  140.             get
  141.             {
  142.                 return new List<Location>{
  143.                                         new Location { City="London", Distance=4789, Country="UK" },
  144.                                         new Location { City="Amsterdam", Distance=4869, Country="Netherland" },
  145.                                         new Location { City="San Francisco", Distance=684, Country="USA" },
  146.                                         new Location { City="Las Vegas", Distance=872, Country="USA" },
  147.                                         new Location { City="Boston", Distance=2488, Country="USA" },
  148.                                         new Location { City="Raleigh", Distance=2363, Country="USA" },
  149.                                         new Location { City="Chicago", Distance=1733, Country="USA" },
  150.                                         new Location { City="Charleston", Distance=2421, Country="USA" },
  151.                                         new Location { City="Helsinki", Distance=4771, Country="Finland" },
  152.                                         new Location { City="Nice", Distance=5428, Country="France" },
  153.                                         new Location { City="Dublin", Distance=4527, Country="Ireland" }
  154.                                     };
  155.             }
  156.         }
  157.     }
  158. }
  159.  
  160.  
  161. using System;
  162. using System.Collections.Generic;
  163. using Extensions;
  164.  
  165. namespace Linq
  166. {
  167.     public class Step1
  168.     {
  169.         public void Execute()
  170.         {
  171.             Console.WriteLine("\nStep 1. Extension methods.\n");
  172.  
  173.             // voorbeeld: extension methods gedefinieerd op Int32
  174.             Console.WriteLine($"Is 6 even? {6.IsEven()}" );
  175.             Console.WriteLine($"Is 7 even? {7.IsEven()}");
  176.             for (int i = 0; i < 10; i++)
  177.             {
  178.                 string even = i.IsEven() ? "even" : "odd";
  179.                 Console.WriteLine($"{i} is {even}");
  180.             }
  181.  
  182.             // voorbeeld: extension methods gedefinieerd op string
  183.             string hello = "Hello!";
  184.             Console.WriteLine($"6 times {hello}, that's {hello.RepeatText(6)}");
  185.  
  186.             string myText = "Please repeat me...";
  187.             Console.WriteLine(myText.RepeatText(2));
  188.  
  189.             // voorbeeld: extension method op IEnumerable<int>
  190.             IList<int> numbers = new List<int> {1, 2, 3, 4, 5};
  191.             Console.WriteLine($"De som is {numbers.CalculateSum()}");
  192.  
  193.             // extension method IsDivisibleBy geeft aan of
  194.             // een geheel getal deelbaar is door een ander geheel getal
  195.             // vervolledig de extension method in de klasse Extension, en vervolledig onderstaande for-loop
  196.             // zodat enkel getallen die deelbaar zijn door 3 worden getoond, maak gebruik van de extension method
  197.             Console.WriteLine("Getallen tussen 1 en 20 deelbaar door 3:");
  198.             for (int i = 1; i <= 20; i++)
  199.                 if (i.IsDivisibleBy(3))
  200.                     Console.WriteLine(i);
  201.  
  202.             Console.WriteLine("Druk op enter om verder te gaan...");
  203.             Console.ReadLine();
  204.         }
  205.     }
  206. }
  207.  
  208.  
  209.  
  210. using System;
  211. using System.Collections.Generic;
  212. using System.Linq;
  213.  
  214. namespace Linq
  215. {
  216.     public class Step2
  217.     {
  218.         public void Execute()
  219.         {
  220.             Console.WriteLine("\nStep 2: Enkele eenvoudige Linq operatoren.\n");
  221.  
  222.             // Enkele Linq methodes op collecties van getallen
  223.             int[] getallen = { 2, 8, 10 };
  224.             Console.WriteLine($"De som is {getallen.Sum()}" );
  225.  
  226.             List<int> myList = new List<int>();
  227.             myList.Add(2);
  228.             myList.Add(10);
  229.             myList.Add(10);
  230.             Console.WriteLine($"De som is van de getallen in de lijst is {myList.Sum()}" );
  231.  
  232.             HashSet<double> getallenSet = new HashSet<double> { 2.5, 8.4, 10.6 };
  233.             getallenSet.Add(2.5);
  234.             getallenSet.Add(8.4);
  235.             getallenSet.Add(10.6);
  236.             Console.WriteLine($"De som van de getallen in de hashset is  {getallenSet.Sum()} ...");
  237.             // vervang "{0}" door een correcte Linq expressie
  238.             Console.WriteLine($"Het minimum in de hashset is  {getallenSet.Min()} ..." );
  239.             Console.WriteLine($"De maximum in de hashset is  {getallenSet.Max()} ...");
  240.  
  241.             Stack<float> getallenStack = new Stack<float>();
  242.             getallenStack.Push(1.5F);
  243.             getallenStack.Push(2.6F);
  244.             getallenStack.Push(5F);
  245.            // float somStack = getallenStack.Sum();
  246.             Console.WriteLine($"De som van de getallen op de stack is  {getallenStack.Sum()} ...");
  247.             // vervang "{0}" door een correcte Linq expressie
  248.             Console.WriteLine($"Het gemiddelde van de getallen op de stack is  {getallenStack.Average()} ...");
  249.             Console.WriteLine($"Het aantal getallen op de stack is  {getallenStack.Count()} ...");
  250.  
  251.             Console.WriteLine("Druk op enter om verder te gaan...");
  252.             Console.ReadLine();
  253.         }
  254.     }
  255. }
  256.  
  257.  
  258.  
  259. using System;
  260. using System.Collections.Generic;
  261. using System.Linq;
  262. using Linq.Models;
  263.  
  264. namespace Linq
  265. {
  266.     public class Step3
  267.     {
  268.         public void Execute()
  269.         {
  270.             Console.WriteLine("\nStep 3: Where en lambda expressies\n");
  271.  
  272.             IEnumerable<Location> placesVisited = TravelOrganizer.PlacesVisited;
  273.             int sumDistances = placesVisited.Sum(l => l.Distance);
  274.             Console.WriteLine($"De som van alle afstanden is {sumDistances} miles" );
  275.  
  276.             int[] results = { 12, 15, 7, 9, 10, 5, 0, 20 };
  277.             // bereken hieronder het aantal results hoger of gelijk aan 10
  278.             int nrOfPasses = results.Count(r => r >= 10);
  279.             Console.WriteLine($"De resultaten bevatten {nrOfPasses} cijfers boven de helft" );
  280.             Console.WriteLine();
  281.  
  282.             string[] cities = {
  283.                                   "London", "Amsterdam", "San Francisco", "Las Vegas", "Boston", "Raleigh", "Chicago",
  284.                                   "Charlestown", "Helsinki", "Nice", "Dublin"
  285.                               };
  286.  
  287.             // filter: steden waarvan de naam langer dan 5 posities
  288.             IEnumerable<string> citiesWithlongNames = cities.Where(c => c.Length > 5);
  289.  
  290.             // onderstaande uit commentaar halen: demo deferred execution
  291.             cities[0] = "Oostende";
  292.  
  293.             Console.WriteLine("Steden met namen langer dan 5 karakters:");
  294.             foreach (var city in citiesWithlongNames)
  295.             {
  296.                 Console.WriteLine(city);
  297.             }
  298.             Console.WriteLine();
  299.  
  300.             // steden waarvan de naam langer dan 5 posities, gesorteerd op naam
  301.             IEnumerable<string> orderedPlaces = cities.Where(c => c.Length > 5).OrderBy(c => c).ToList();
  302.             // cities[0] = "Oostende";
  303.             Console.WriteLine("Gesorteerde lijst van steden met namen langer dan 5 karakters:");
  304.             foreach (var city in orderedPlaces)
  305.             {
  306.                 Console.WriteLine(city);
  307.             }
  308.             Console.WriteLine();
  309.  
  310.             // steden waarvan de naam langer is dan 5 posities en starten met de letter 'S'
  311.             // gesorteerd dalend op lengte van de naam, en dan op de naam zelf
  312.             string[] cities2 = {
  313.                                   "London", "Amsterdam", "San Francisco", "Las Vegas", "Boston", "Raleigh", "Chicago",
  314.                                   "Charlestown", "Helsinki", "Nice", "Dublin", "San Anselmo", "San Diego", "San Mateo"
  315.                               };
  316.             // vul selectedCities adhv een gepaste Linq expressie
  317.             IEnumerable<string> selectedCities =
  318.                 cities2.Where(c => c.StartsWith("S") && c.Length > 5).OrderByDescending(c => c.Length).ThenBy(c => c);
  319.  
  320.             Console.WriteLine("Steden met namen langer dan 5 karakters, en beginnend met 'S', dalend gesorteerd op lengte van de naam, dan op naam:");
  321.             // schrijf hier de steden uit adhv een for each
  322.             foreach (string city in selectedCities)
  323.                 Console.WriteLine(city);
  324.             Console.WriteLine();
  325.  
  326.             Console.WriteLine("Druk op enter om verder te gaan...");
  327.             Console.ReadLine();
  328.         }
  329.     }
  330. }
  331.  
  332.  
  333.  
  334. using System;
  335. using System.Collections.Generic;
  336. using System.Linq;
  337. using Linq.Models;
  338.  
  339. namespace Linq
  340. {
  341.     public class Step4
  342.     {
  343.         public void Execute()
  344.         {
  345.             Console.WriteLine("\nStep 4: Linq Select, var en anonieme types\n");
  346.  
  347.             IEnumerable<Location> placesVisited = TravelOrganizer.PlacesVisited;
  348.             int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  349.  
  350.             // simpele transaformatie van collectie van int-s
  351.             IEnumerable<int> newNumbers = numbers.Select(g => g + 1);
  352.             PrintCollection("De gewijzigde lijst van getallen:", newNumbers);
  353.  
  354.             // transformatie van Location-s naar int-s
  355.             IEnumerable<int> cityLengths = placesVisited.Select(c => c.City.Length);
  356.             PrintCollection("Lengte van de namen van de steden:", cityLengths);
  357.  
  358.             // transformatie van Location-s naar CityDistance-s, object initializer
  359.             IEnumerable<CityDistance> cityDistances = placesVisited.Select(
  360.                      c => new CityDistance
  361.                      {
  362.                          Name = c.City,
  363.                          Country = c.Country,
  364.                          DistanceInKm = (int)(c.Distance * 1.61)
  365.                      });
  366.  
  367.             PrintCollection("Afstanden in km:", cityDistances);
  368.             Console.WriteLine();
  369.  
  370.             // transformatie naar een anoniem type met de props Name, Country en DistanceInKm
  371.             var anonymousCities = placesVisited.Select(c => new
  372.             {
  373.                 Name = c.City,
  374.                 c.Country,
  375.                 DistanceInKm = c.Distance*1.61
  376.             });
  377.             PrintCollection("Anonieme types:", anonymousCities);
  378.             Console.WriteLine();
  379.  
  380.             Console.WriteLine("Druk op enter om verder te gaan...");
  381.             Console.ReadLine();
  382.         }
  383.  
  384.         // generische methode PrintCities<T>
  385.         public static void PrintCollection<T>(string title, IEnumerable<T> cities)
  386.         {
  387.             Console.WriteLine();
  388.             Console.WriteLine($"----- {title} -----");
  389.             if (!cities.Any())
  390.                 Console.WriteLine("geen steden...");
  391.             else
  392.                 foreach (var c in cities)
  393.                     Console.WriteLine(c);
  394.             Console.WriteLine();
  395.         }
  396.     }
  397. }
  398.  
  399.  
  400.  
  401. using System;
  402. using System.Collections.Generic;
  403. using System.Linq;
  404. using Linq.Models;
  405.  
  406. namespace Linq
  407. {
  408.     public class Step5
  409.     {
  410.         public void Execute()
  411.         {
  412.             Console.WriteLine("\nStep 5 : Nog meer handige LINQ operatoren\n");
  413.  
  414.              IEnumerable<Location> placesVisited = TravelOrganizer.PlacesVisited;
  415.  
  416.             // FirstOrDefault: vind de verste stad
  417.             Location furthest = placesVisited.OrderByDescending(c => c.Distance).FirstOrDefault();
  418.             Console.WriteLine($"Verste stad: {furthest}");
  419.             Console.WriteLine();
  420.  
  421.             // Skip n Take: cities 2 - 5
  422.             IEnumerable<Location> locations = placesVisited.Skip(1).Take(5);
  423.             Step4.PrintCollection("Cities skip 1 take 5", locations);
  424.             Console.WriteLine();
  425.  
  426.             // Any/All:
  427.             Console.WriteLine($"Is er een stad op meer dan 5000 miles afstand? {placesVisited.Any(c => c.Distance > 5000)}" );
  428.             Console.WriteLine($"Liggen alle steden op zijn minst 2000 miles ver? {placesVisited.All(c => c.Distance >= 2000)}");
  429.             Console.WriteLine();
  430.  
  431.             // SelectMany: flat list of countries and cities with use of collection initializer
  432.             var flatListOfNames = placesVisited.SelectMany(c => new List<string> { c.City, c.Country });
  433.             Console.WriteLine("Alle steden en landen in 1 lijst:");
  434.             foreach (var n in flatListOfNames)
  435.                 Console.WriteLine($"- {n} -");
  436.             Console.WriteLine();
  437.  
  438.             // Groeperen van gegevens: per land, de steden die behoren tot het land...
  439.             var overzicht = placesVisited.GroupBy(l => l.Country, l => l.City);
  440.             foreach (var overzichtsGroep in overzicht)
  441.             {
  442.                 Console.WriteLine(overzichtsGroep.Key);
  443.                 foreach (string city in overzichtsGroep)
  444.                     Console.WriteLine($"  - {city}" );
  445.             }
  446.             Console.WriteLine();
  447.  
  448.             Console.WriteLine("Druk op enter om verder te gaan...");
  449.             Console.ReadLine();
  450.         }
  451.     }
  452. }
  453.  
  454.  
  455.  
  456. using System;
  457. using System.Collections.Generic;
  458. using Linq.Models;
  459. using System.Linq;
  460.  
  461. namespace Linq
  462. {
  463.     public class Step6
  464.     {
  465.         public void Execute()
  466.         {
  467.             Console.WriteLine("\nStep 6 : Exercises\n");
  468.             IEnumerable<Location> placesVisited = TravelOrganizer.PlacesVisited;
  469.  
  470.             // De gemiddelde afstand van de steden
  471.             Console.WriteLine($"Gemiddelde afstand van de steden is {placesVisited.Average(p => p.Distance):0} miles");
  472.  
  473.             // De afstand van de verste stad
  474.             Console.WriteLine($"De verste stad ligt op {placesVisited.Max(p => p.Distance):0} miles");
  475.  
  476.             // De verste stad in de USA
  477.             Console.WriteLine($"De verste stad in de USA is {placesVisited.OrderByDescending(p => p.Distance).FirstOrDefault(p => p.Country == "USA")}");
  478.  
  479.             // Geef de namen van de landen met steden die niet in de USA liggen en op minder dan 4600 miles afstand liggen
  480.             IEnumerable<string> nearbyNonUsaCities =
  481.                 placesVisited
  482.                 .Where(p => p.Country != "USA" && p.Distance < 4600)
  483.                 .Select(p => p.Country)
  484.                 .Distinct();
  485.             Step4.PrintCollection("Dichte steden buiten de USA", nearbyNonUsaCities);
  486.  
  487.             // Een gesorteerde lijst van alle landen (elk land komt slechts 1 keer voor in de lijst)
  488.             IEnumerable<string> countries = placesVisited
  489.                 .Select(p => p.Country)
  490.                 .Distinct()
  491.                 .OrderBy(c => c);
  492.             Step4.PrintCollection("Alle landen in de lijst:", countries);
  493.  
  494.             // Maak een lijst van anonieme objecten die de properties City en InUSA hebben.
  495.             // InUSA staat op true voor een city binnen de USA, anders op false
  496.             var cityInfo = placesVisited
  497.                 .Select(p => new
  498.             {
  499.                 p.City,
  500.                 InUSA = p.Country == "USA"
  501.             });
  502.             Console.WriteLine("Welke steden liggen in de USA?");
  503.             Step4.PrintCollection("Anonieme type voor landen:", cityInfo);
  504.  
  505.             // Maak een array van CityDistance objecten voor alle Locations die in de USA liggen
  506.             CityDistance[] cityDistances = placesVisited
  507.                 .Where(p => p.Country == "USA").
  508.                 Select(p => new CityDistance
  509.                 {
  510.                     Name = p.City,
  511.                     Country = p.Country,
  512.                     DistanceInKm = (int)(p.Distance * 1.6)
  513.                 }).ToArray();
  514.  
  515.             Step4.PrintCollection("CityDistances voor steden in USA:", cityDistances);
  516.  
  517.             Console.WriteLine("Druk op enter om verder te gaan...");
  518.             Console.ReadLine();
  519.  
  520.         }
  521.     }
  522. }
  523.  
  524.  
  525.  
  526. using System;
  527. using System.Collections.Generic;
  528. using SportsStore.Models;
  529. using SportsStore.Data;
  530. using SportsStore.ViewModels;
  531. using System.Linq;
  532.  
  533. namespace SportsStore
  534. {
  535.     public class Program
  536.     {
  537.         public static void Main(string[] args)
  538.         {
  539.             IEnumerable<Category> categories = DataSourceProvider.Categories;
  540.             IEnumerable<Customer> customers = DataSourceProvider.Customers;
  541.             IEnumerable<Product> products = DataSourceProvider.Products;
  542.  
  543.             #region Toon de gemiddelde prijs van de producten
  544.             Console.WriteLine($"De gemiddelde prijs van de producten is { products.Average(p => p.Price):0.00}");
  545.             Console.ReadLine();
  546.             #endregion
  547.  
  548.             #region Toon hoeveel categorieen en hoeveel customers er zijn
  549.             Console.WriteLine($"Er zijn {categories.Count()} categorieen.");
  550.             Console.WriteLine($"Er zijn {customers.Count()} customers.");
  551.             Console.ReadLine();
  552.             #endregion
  553.  
  554.             #region Hoeveel karakters telt de langste productnaam?
  555.             Console.WriteLine($"De langste productnaam is { products.Max(p => p.Name.Length)} karakters lang.");
  556.             Console.ReadLine();
  557.             #endregion
  558.  
  559.             #region Toon de naam van het product met de langste productnaam
  560.  
  561.             string productnaam = products
  562.                 .OrderByDescending(p => p.Name.Length)
  563.                 .FirstOrDefault()
  564.                 .Name;
  565.             Console.WriteLine($"De langste productnaam is {productnaam}.");
  566.             Console.ReadLine();
  567.             #endregion
  568.  
  569.             #region Toon alle customers gesorteerd op naam, en vervolgens dalend op voornaam
  570.             IEnumerable<Customer> customersSorted = customers
  571.                 .OrderBy(c => c.Name)
  572.                 .ThenByDescending(c => c.FirstName);
  573.             PrintCustomers("Klanten gesorteerd op naam, en dan dalend op voornaam:", customersSorted);
  574.             Console.ReadLine();
  575.             #endregion
  576.  
  577.             #region Toon alle producten die meer dan 92.5 dollar kosten, dalend op prijs
  578.             IEnumerable<Product> expensiveProducts =
  579.                 products.Where(p => p.Price > 92.5M)
  580.                 .OrderByDescending(p => p.Price);
  581.             PrintProducts("Producten die meer dan 92.5 dollar kosten", expensiveProducts);
  582.             Console.ReadLine();
  583.             #endregion
  584.  
  585.             #region  Toon de categorieen die meer dan twee producten bevatten
  586.             IEnumerable<Category> myCategories =
  587.                 categories.Where(c => c.Products.Count > 2);
  588.             PrintCategories("Categorieen met meer dan twee producten", myCategories);
  589.             Console.ReadLine();
  590.             #endregion
  591.  
  592.             #region  Maak een lijst van strings die alle productnamen bevat
  593.             IEnumerable<string> productNamen = products.Select(p => p.Name);
  594.             PrintStrings("Namen van producten", productNamen);
  595.             Console.ReadLine();
  596.             #endregion
  597.  
  598.             #region Maak een lijst van namen van steden waar customers wonen (zonder dubbels)
  599.             IEnumerable<string> steden = customers
  600.                 .Select(p => p.City.Name)
  601.                 .Distinct();
  602.             PrintStrings("Namen van steden waar klanten wonen", steden);
  603.             Console.ReadLine();
  604.             #endregion
  605.  
  606.             #region Maak een lijst van ProductViewModels (vorm elk product om tot een productViewModel)
  607.             IEnumerable<ProductViewModel> pvm =
  608.                 products
  609.                 .Select(p => new ProductViewModel
  610.                 {
  611.                     Name = p.Name,
  612.                     Price = p.Price,
  613.                     PriceEuro = p.Price * 0.9M
  614.                 });
  615.             Console.WriteLine("Lijst van ProductViewModels");
  616.             foreach (var p in pvm)
  617.             {
  618.                 Console.WriteLine($"{p.Name} kost { p.Price:0.00} dollar, dat is {p.PriceEuro:0.00} euro");
  619.             }
  620.             Console.WriteLine();
  621.             Console.ReadLine();
  622.             #endregion
  623.  
  624.             #region Maak gebruik van een anoniem type
  625.             // maak een lijst die de naam, de voornaam
  626.             // en de naam van de stad van elke customer bevat
  627.             var customerDetails = customers.Select(c => new
  628.             {
  629.                 c.Name,
  630.                 c.FirstName,
  631.                 CityName = c.City.Name,
  632.             });
  633.             Console.WriteLine("Details van customers");
  634.             foreach (var c in customerDetails)
  635.             {
  636.                 Console.WriteLine($"{c.Name} {c.FirstName} woont in {c.CityName}");
  637.             }
  638.             Console.ReadLine();
  639.             #endregion
  640.  
  641.             #region Pas vorige query aan
  642.             // zodat het anoniem type nu ook een boolse property bevat
  643.             // die aangeeft of de customer reeds orders heeft
  644.             var customerDetails2 = customers.Select(c => new
  645.             {
  646.                 c.Name,
  647.                 c.FirstName,
  648.                 CityName = c.City.Name,
  649.                 HasOrders = c.Orders.Any()
  650.             });
  651.             Console.WriteLine("Details van customers");
  652.             foreach (var c in customerDetails2)
  653.             {
  654.                 Console.WriteLine($"{c.Name} {c.FirstName} woont in {c.CityName} en heeft {(c.HasOrders ? String.Empty : "geen ")} bestellingen");
  655.             }
  656.             Console.ReadLine();
  657.             #endregion
  658.  
  659.             #region Geef de namen van de categorieën met enkel producten die de letter 'o' in de naam hebben
  660.             IEnumerable<string> oCategories = categories
  661.                 .Where(c => c.Products.All(p => p.Name.Contains("o")))
  662.                 .Select(c => c.Name);
  663.             PrintStrings("Categorieen waarbij alle producten de letter 'o' bevatten", oCategories);
  664.             Console.ReadLine();
  665.             #endregion
  666.  
  667.             #region Geef het eerste product die de letter 'f' bevat, vertrek van de lijst van producten gesorteerd op naam
  668.             Product myProductF = products.OrderBy(p => p.Name)
  669.                 .FirstOrDefault(p => p.Name.Contains("f"));
  670.             PrintProduct("Eerste product met letter f", myProductF);
  671.             Console.ReadLine();
  672.             #endregion
  673.  
  674.             #region Maak een lijst van customers die reeds een product met de naam Football hebben besteld
  675.             IEnumerable<Customer> customersWithFootball = customers
  676.                 .Where(c => c.Orders.SelectMany(o => o.OrderLines)
  677.                 .Select(o => o.Product.Name).Contains("Football"));
  678.             //OR
  679.             //IEnumerable<Customer> customersWithFootball = customers
  680.             //    .Where(c => c.Orders.Any(o => o.OrderLines.Any(ol => ol.Product.Name == "Football")));
  681.             PrintCustomers("Klanten die reeds Football bestelden:", customersWithFootball);
  682.             Console.ReadLine();
  683.             #endregion
  684.  
  685.             #region Toon de voornaam van de customer met naam Student1.
  686.             // Geef een gepaste melding indien
  687.             //  - er geen customers zijn met die naam,
  688.             //  - of indien er meerdere customers zijn met die naam  
  689.             // Test je code ook met Student0 en Student9
  690.             string naam = "Student1";
  691.             try
  692.             {
  693.                 var customer = customers.SingleOrDefault(c => c.Name == naam);
  694.                 if (customer != null)
  695.                     Console.WriteLine($"Customer {customer.Name} { customer.FirstName}");
  696.                 else
  697.                     Console.WriteLine($"Er is geen customer met de naam {naam}");
  698.             }
  699.             catch (Exception)
  700.             {
  701.                 Console.WriteLine($"Meerdere customers noemen {naam}");
  702.             }
  703.             Console.ReadLine();
  704.         }
  705.         #endregion
  706.  
  707.         #region Print helpmethodes
  708.         private static void PrintCustomers(string message, IEnumerable<Customer> customers)
  709.         {
  710.             Console.WriteLine(message);
  711.             foreach (Customer c in customers)
  712.                 Console.WriteLine($"{ c.Name} {c.FirstName}");
  713.             Console.WriteLine();
  714.         }
  715.  
  716.         private static void PrintProducts(string message, IEnumerable<Product> products)
  717.         {
  718.             Console.WriteLine(message);
  719.             foreach (Product p in products)
  720.                 Console.WriteLine($"{ p.Name}, prijs: { p.Price}");
  721.             Console.WriteLine();
  722.         }
  723.  
  724.         private static void PrintCategories(string message, IEnumerable<Category> categories)
  725.         {
  726.             Console.WriteLine(message);
  727.             foreach (Category c in categories)
  728.                 Console.WriteLine(c.Name);
  729.             Console.WriteLine();
  730.         }
  731.  
  732.         private static void PrintStrings(string message, IEnumerable<string> strings)
  733.         {
  734.             Console.WriteLine(message);
  735.             foreach (string s in strings)
  736.                 Console.WriteLine(s);
  737.             Console.WriteLine();
  738.         }
  739.  
  740.         private static void PrintProduct(string message, Product product)
  741.         {
  742.             Console.WriteLine(message);
  743.             if (product == null)
  744.                 Console.WriteLine("Product is null");
  745.             else
  746.                 Console.WriteLine($"{ product.Name}, prijs: {product.Price}");
  747.  
  748.             Console.WriteLine();
  749.         }
  750.         #endregion
  751.  
  752.     }
  753. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement