repl.it
C#

No description

fork
loading
Files
  • main.cs
  • Book.cs
  • BookRepository.cs
  • main.exe
  • notes.txt
  • Nullable.cs
main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Collections.Generic;
using System.Linq;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            
var books = new BookRepository().GetBooks();
            // Where() is used to filter collections
            // lambda expression and chaining Where() OrderBy() Select()
            // sorted by title 


            // first method on Lambda expression  (LastOrDefault is for last item) 
            var bookFirst = books.FirstOrDefault(b => b.Title == "C# Advanced Topics"); 
            Console.WriteLine(bookFirst.Title + " " + bookFirst.Price);  

            Console.WriteLine(); // breakline
            

            // skipping recored method on Lambda expression
            // skip 2 book objects and take 3
            var pagedBooks = books.Skip(2).Take(3);

            foreach (var pagedBook in pagedBooks)
            {
                Console.WriteLine(pagedBook.Title);
            }

            Console.WriteLine(); // breakline

            // count method 

            var countTotalBooks = books.Count();
            Console.WriteLine($"There a total of {countTotalBooks} books");

            Console.WriteLine(); // breakline

            // max value (price

            var bookMaxPrice = books.Max(b => b.Price);
            Console.WriteLine($"The most expensive book is ${bookMaxPrice} dollars");

            var bookMinPrice = books.Min(b => b.Price);
            Console.WriteLine($"The least expensive book is ${bookMinPrice} dollars");

            var totalBookPrices = books.Sum(b => b.Price);
            Console.WriteLine($"Total book prices ${totalBookPrices} dollars");

            Console.WriteLine(); // breakline

            // LINQ Extension Methods
            var cheapBooks = books
                               .Where(b => b.Price < 10)
                               .OrderBy(b => b.Title)
                               .Select(b => b.Title); 
            
            
            

            foreach (var book in cheapBooks)
                Console.WriteLine(book);  // book is just sttring because of Select()
                // Console.WriteLine(book.Title + " " + book.Price);
            
    
    }
  }
}