How it works...

From steps 1 to 4, we created a blank solution using Visual Studio 2017 and gave it a location and a proper meaningful name. Then, from steps 5 to 9, we added a new .NET Standard 2.0 library to the blank solution. As usual, we gave it a proper and meaningful name. 

In steps 12 and 13, we renamed the default Class1.cs template to TelephoneBook.cs. It's a good practice to keep both the class and filename the same. This is more readable and understandable when you come back to your code. In step 16, we added two namespaces to the code. System.Collections.Generic will get you the List<T> class used in the code and System.Linq gives you more control over those generic collections by allowing the LINQ functionality. 

In step 17, we introduced a private variable type of List<string>. In step 18, we initiated the variable and added some data to the list.  Everything is done inside the constructor of the TelephoneBook() class. In step 19, we created a method that returns the list of contacts. It has one line of code that returns the populated list. 

Again, in step 20, we created a method that takes a string as a parameter. The parameter is the last name and we have used LINQ queries in this line: 

var contacts = _contactList.Where(c => c.Contains(lastName)).ToList();

We have used a Where clause to filter down the list and used an inline function to pass the lastName parameter to the operation. Finally, we output the result as a list and returned the result at the end of the method. 

In step 21, we created a method that ordered the list using LINQ. The GetSortedContacts() takes one Boolean parameter and it is optional. C# has supported optional parameters since C# 4.0. 

var sorted = _contactList.OrderBy(c => c).ToList();

The previous line of code uses the OrderBy() method in the list to order the list in ascending order and pass it as a list. If we need it in descending order, just pass the method parameter as false

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.223.123