Introduction to LINQ in C#

Tutorial 2 of 5

Introduction

The goal of this tutorial is to introduce you to Language Integrated Query (LINQ), a powerful feature in C# for manipulating data. By the end of this tutorial, you will understand the basics of how to use LINQ to filter, query, and transform data.

What You'll Learn

  • The basics of LINQ in C#
  • How to use LINQ to filter and query data
  • How to use LINQ to transform data

Prerequisites

  • Basic knowledge of C#
  • Familiarity with .NET framework

Step-by-Step Guide

What is LINQ?

LINQ stands for Language Integrated Query, which means it's a part of the C# language itself. It allows you to write queries directly in your C# code to manipulate data in a more readable and concise way.

LINQ Operations

There are several operations you can perform with LINQ, including:

  • Filtering
  • Sorting
  • Grouping
  • Joining
  • Aggregation

Syntax

There are two syntaxes you can use with LINQ:

  • Query Syntax: This is similar to SQL and is generally more readable.
  • Method Syntax: This is a more functional approach and can be more concise.

Code Examples

Let's look at some practical examples.

Example 1: Filtering with LINQ

// Here we have a list of numbers
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// We can use LINQ to filter out the even numbers
var evenNumbers = from num in numbers
                  where num % 2 == 0
                  select num;

// The result will be a list of the even numbers: 2, 4, 6, 8, 10

Example 2: Transforming Data with LINQ

// We have a list of strings
List<string> words = new List<string> { "apple", "banana", "cherry" };

// We can use LINQ to transform each string to uppercase
var upperWords = from word in words
                 select word.ToUpper();

// The result will be a list of the words in uppercase: "APPLE", "BANANA", "CHERRY"

Summary

In this tutorial, you've learned the basics of LINQ in C#, including how to use LINQ to filter and transform data. To continue your learning, you might want to explore more complex LINQ operations, like sorting, grouping, joining, and aggregation.

Practice Exercises

Exercise 1

Given a list of numbers, use LINQ to find all numbers that are divisible by 3.

Exercise 2

Given a list of strings, use LINQ to find all strings that start with the letter 'a'.

Solutions

Solution 1

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

This will output 3, 6, 9.

Solution 2

List<string> words = new List<string> { "apple", "banana", "cherry", "avocado", "mango" };
var startWithA = from word in words
                 where word.StartsWith("a")
                 select word;

This will output "apple", "avocado".