Introduction to LINQ and Lambda Expressions

Tutorial 4 of 5

Introduction

Welcome to this tutorial on Language INtegrated Query (LINQ) and Lambda Expressions in C#. These tools provide powerful querying and data manipulation capabilities that can make your code cleaner and more efficient.

Here's what you'll learn:

  • What is LINQ and how it works
  • Understanding and using Lambda Expressions
  • Combining LINQ and Lambda Expressions for powerful data manipulation

Prerequisites:

  • Basic knowledge of C# programming
  • Familiarity with collections in C#

Step-by-Step Guide

LINQ

LINQ is a set of features introduced in .NET Framework 3.5 that provides a simple and consistent way for querying and manipulating data. It can work with data from a variety of sources, like SQL databases, XML documents, ADO.NET Datasets, and any collection of objects supporting IEnumerable or the generic IEnumerable interface.

LINQ query syntax

Here is a simple LINQ query that returns all even numbers from a list:

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbers = from num in numbers
                  where num % 2 == 0
                  select num;

This LINQ query consists of three parts:

  • from num in numbers specifies the data source.
  • where num % 2 == 0 applies a filter.
  • select num specifies the type of values to return.

Lambda Expressions

Lambda expressions are anonymous functions you can use to create delegates or expression tree types. They use the lambda operator =>, read as "goes to".

Here's a simple example of a lambda expression that returns true if a number is even:

Func<int, bool> isEven = num => num % 2 == 0;

In this example, num => num % 2 == 0 is the lambda expression. num is the input parameter and num % 2 == 0 is the expression body.

Combining LINQ and Lambda Expressions

You can use lambda expressions with LINQ for more concise and flexible code. Here's the previous LINQ query rewritten using a lambda expression:

var evenNumbers = numbers.Where(num => num % 2 == 0);

Code Examples

Example 1: Filtering a list of strings

List<string> words = new List<string>() { "apple", "banana", "cherry", "date", "elderberry" };
var shortWords = words.Where(word => word.Length <= 5);

In this example, word => word.Length <= 5 is a lambda expression that returns true for words of length 5 or less. shortWords will contain "apple", "date", and "cherry".

Example 2: Ordering a list of integers

List<int> numbers = new List<int>() { 5, 7, 2, 4, 9, 6 };
var orderedNumbers = numbers.OrderBy(num => num);

Here, num => num is a lambda expression that sorts the numbers in ascending order. orderedNumbers will be { 2, 4, 5, 6, 7, 9 }.

Summary

In this tutorial, you learned about LINQ and Lambda Expressions in C#, and how to use them for querying and manipulating data. Your next step could be learning about more complex LINQ operations, such as grouping and joining.

Practice Exercises

Exercise 1

Write a LINQ query that returns the squares of all numbers in a list.

Solution:

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
var squares = numbers.Select(num => num * num);

Exercise 2

Write a LINQ query that returns all words in a list that start with a certain letter.

Solution:

List<string> words = new List<string>() { "apple", "banana", "cherry", "date", "elderberry" };
char letter = 'b';
var filteredWords = words.Where(word => word.StartsWith(letter));

This will return "banana".