Lesson # 13. Lists. LINQ Extension Methods, Lambda expressions

Programming on c sharp in Microsoft Visual Studio. Using Lists. LINQ Extension Methods, Lambda expressions

Lesson # 13. Theory

List<T> Class Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

List Definition:
List<int> numList = new List<int> { 1,9,2,6,3 }; // of integer type
var nameList = new List<string> { "Doug", "Sally", "Sue" }; // of string type

To output the list:

foreach (var k in numList)
     Console.WriteLine(k);

List generators:

// Generate a list from 1 to 10
var L = new List<int>();
L.AddRange(Enumerable.Range(1, 10));
foreach (var k in L)
    Console.WriteLine(k);
Lambda expressions
  • LINQ — Language Integrated Query (pronounced «link») is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages.
  • The set of query operators defined by LINQ is exposed to the user as the Standard Query Operator (SQO) API. The main query operators are Select, Where, Aggregate (etc.).
  • Delegate that is assigned a Lambda expression:
  •  class Program
        {
            delegate double doubleIt(double val);
            static void Main(string[] args)
            {
                doubleIt dblIt = x => x * 2;
                Console.WriteLine($"5 * 2 = {dblIt(5)}");
            }
    
    Where query

    Problem: find all the even numbers in the list:

    List<int> numList = new List { 1,9,2,6,3 };
     
    var evenList = numList.Where(a => a % 2 == 0).ToList();
     
    foreach (var j in evenList)
        Console.WriteLine(j);
    

    Problem: Add values in a range to a list

    List<int> numList = new List<int> { 1, 9, 2, 6, 3 };
    var rangeList = numList.Where(x => (x > 2) || (x < 9)).ToList();
    
    foreach (var k in rangeList)
       Console.WriteLine(k);
    

    Problem: Find all names starting with s

    var nameList = new List<string> { "Doug", "Sally", "Sue" };
    
    var sNameList = nameList.Where(x => x.StartsWith("S"));
    
    foreach (var m in sNameList)
        Console.WriteLine(m); // Sally Sue
    
    Select query

    Select allows us to execute a function on each item in a list.

    var lst= new List<int>();
    lst.AddRange(Enumerable.Range(1, 10));
     
    var squares = lst.Select(x => x * x);
     
    foreach (var l in squares)
        Console.Write(l+" "); // 1 4 9 16 25 36 49 64 81 100
    
    ZIP

    Zip applies a function to two lists
    Problem: Add values in 2 lists together

    var listOne = new List(new int[] { 1, 3, 4});
    var listTwo = new List(new int[] { 4, 6, 8});
     
    var sumList = listOne.Zip(listTwo, (x, y) => x + y).ToList();
     
    foreach (var n in sumList)
       Console.WriteLine(n); // 5 9 12
    
    AGGREGATE

    Aggregate performs an operation on each item in a list and carries the results forward
    Problem: Sum values in a list

    var numList2 = new List<int>() { 1, 2, 3, 4, 5 };
    Console.WriteLine("Sum : {0}",
       numList2.Aggregate((a, b) => a + b)); // Sum : 15
    
    AVERAGE

    AsQueryable allows you to manipulate the collection with the Average function
    Problem: Get the average of a list of values

    var numList3 = new List<int>() { 1, 2, 3, 4, 5 };
     
    Console.WriteLine("AVG : {0}", 
         numList3.AsQueryable().Average()); // AVG : 3
    
    ALL

    Determines if all items in a list meet a condition

    var numList4 = new List() { 1, 2, 3, 4, 5 };
    
    Console.WriteLine("All > 3 : {0}",
       numList4.All(x => x > 3)); // All > 3 : False
    
    ANY

    Determines if any items in a list meet a condition

    var numList5 = new List<int>() { 1, 2, 3, 4, 5 };
     
    Console.WriteLine("Any > 3 : {0}",
       numList5.Any(x => x > 3)); // Any > 3 : True
    

    Labs and Tasks

    Task 1:

    To do: Read the theoretical material and complete the tasks.
    1. Generate a list from -5 to 10 and print it out within single line
      
    Expected output:

    // 1.
    -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10
    

    2. Using delegate create a function to add 1 to some number.

    Expected output:

    // 2.
    3 + 1 = 4
    

    3. Create a list of positive and negative numbers. First find all negative numbers in the list and then the elements divisible by 3 (Where).

    Expected output:

    // 3.
    The list:
    -5 1 9 -2 6 -3 
    result 1:
    -5 -2 -3
    result 2:
    9 6 -3
    

    4. Create a list of names: «Ivan», «John», «Boris», «Bony». At first, find all names ending with «n», and after — all the names containing «Bo».

    Expected output:

    // 4.
    The list:
    Ivan John Boris Bony
    result 1:
    Ivan John
    result 1:
    Boris Bony
    

    5. Generate a list from -5 to 5. At first, cube all the items af the list, and then subtract 3 from all the items.

    Expected output:

    // 5.
    -5 -4 -3 -2 -1 0 1 2 3 4 5
    result 1:
    -125 -64 -27 -8 -1 0 1 8 27 64 125
    result 2:
    -8 -7 -6 -5 -4 -3 -2 -1 0 1 2
    

    6. Two lists are given: 2, 4, 8 and 9, 1, 5. Get a new list by substructing squared items of the second list from squared items of the first list (zip).

    Expected output:

    // 6.
    -77  15  39
    

    7. The list is given. Calculate a multiplication of the list items, using Aggregate function.

    Expected output:

    // 7.
    2  4  8  9  1  5
    Product : 2880
    

    8. The list is given. Print True if all the items are divisable by 3, and False otherwise.

    Expected output:

    // 8.
    3  12  18  9
    All are divisable by 3 : True
    

    [Solution and Project name: Lesson_13Task1, file name L13Task1.cs]

    Task 2:

    To do: Download the file in.txt and place it into the folder of your project executable files (~/bin/Debug).
    1. Create a function to output all the positive elements from that file. You should use LINQ Where method.
    2. Create a function to return the greatest number from all the odd elements from the file. You should use LINQ Where and Max methods.  

    Note 1: You should use FileMode.Open mode and BinaryReader class to read from a file.
    Note 2: You should use the List type to manage the numbers. To add the numbers into the list:

    while (br.PeekChar() != -1)
                {
                    L1.Add(br.ReadInt32()); // L1 is a name of list
                }

    Expected output:

    // Positive elements:
    7 4 2 9 8 4 9 9 1 3
    // The greatest from odd numbers:
    9
    

    [Solution and Project name: Lesson_13Task2, file name L13Task2.cs]