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…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Introduces 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 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".

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help