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