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.
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.
There are several operations you can perform with LINQ, including:
There are two syntaxes you can use with LINQ:
Let's look at some practical examples.
// 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
// 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"
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.
Given a list of numbers, use LINQ to find all numbers that are divisible by 3.
Given a list of strings, use LINQ to find all strings that start with the letter 'a'.
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.
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".