C# Lambda Part 2


This entry is part 2 of 3 in the series C# Lambda

In this second post on Lambda, we are going to use a more practical example of using Lambda expressions. This example is based on the instructional video at Udemy.com by Mosh Hamedani in his C# Advanced series (the third one of three).

Let’s start with a class that defines Book. This is a more practical example because quite often we are working with our classes and lists of our classes. Here we use an example of Book but it could be any class that we have such as People or InventoryItems or Products and so on. We start with defining our class: Book.

    class Book
    {
        public string Title { get; set; }
        public int Price { get; set; }
    }

Next we can create another class that stores a list of books.

    class BookRepository
    {
        public List<Book> GetBooks()
        {
            return new List<Book>
                {
                    new Book() { Title ="bk 1", Price = 5},
                    new Book() { Title = "bk 2", Price = 6 },
                    new Book() { Title = "bk 3", Price = 17 }
                };
        }
    }

Without Lambda Expressions

In our program we want to get a list of books, without using lambda expressions. How would we do that? First we need to get the list of our books and store that list in a variable called books. Next we can use a filter called FindAll(). FindAll() takes n argument. What kind of argument?

Here is another screenshot.

FindAll() needs a predicate of type book. A predicate is a delegate that points to a method that gets a book, in this case, and returns a boolean value specifying if a given condition was satisfied. FindAll() will iterate the collection and for each book in the collection it will pass that book to the function, IsCheaperThan10Dollars in this case, and determine if the condition was satisfied or not. If yes, then FindAll() will return that book in the list of results. It is a filter. It is like the WHERE clause in SQL.

        static void Main(string[] args)
        {
            var books = new BookRepository().GetBooks();
            var cheapBooks = books.FindAll(IsCheaperThan10Dollars);
            foreach (var book in cheapBooks)
            {
                Console.WriteLine(book.Title);
            } 
        }
        static bool IsCheaperThan10Dollars(Book book)
        {   // this is a predicate function
            return book.Price < 10;
        }

Using Lambda Expression

Now let’s shorten our code. We can use a Lambda expression instead of writing a method. We can get rid of the function we wrote and just use a Lambda expression. The variable cheapBooks.

        static void Main(string[] args)
        {
            var books = new BookRepository().GetBooks();
            var cheapBooks = books.FindAll(b => b.Price < 10);
            foreach (var book in cheapBooks)
            {
                Console.WriteLine(book.Title);
            }
            Console.ReadKey();
        }

Let’s put back the type instead of using type inference.

        static void Main(string[] args)
        {
            List<Book> books = new BookRepository().GetBooks();
            List<Book> cheapBooks = books.FindAll(b => b.Price < 10);
            foreach (var book in cheapBooks)
            {
                Console.WriteLine(book.Title);
            }
            Console.ReadKey();
        }

Here is our output in the console. We only get the cheap books.

Series Navigation<< C# Lambda IntroductionC# Lambda Part 3 >>