C# / C# Collections and Generics
Introduction to LINQ and Lambda Expressions
This tutorial introduces you to the powerful querying and data manipulation capabilities of LINQ and Lambda Expressions in C#. You'll learn how to write cleaner, more efficient co…
Section overview
5 resourcesIntroduces collections and generics to handle and manipulate data efficiently.
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
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 numbersspecifies the data source.where num % 2 == 0applies a filter.select numspecifies 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".
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article