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

Дата изменения: 26 мая 2021
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 { 1,9,2,6,3 }; // of integer type
var nameList = new List { "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:

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)}");
        }

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

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:

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_13Task, file name L13Task.cs]

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

*
*


Вставить формулу как
Блок
Строка
Дополнительные настройки
Цвет формулы
Цвет текста
#333333
Используйте LaTeX для набора формулы
Предпросмотр
\({}\)
Формула не набрана
Вставить