-
Notifications
You must be signed in to change notification settings - Fork 5
LINQ Basics
Sann Lynn Htun edited this page Nov 22, 2024
·
2 revisions
LINQ (Language Integrated Query) in C# provides a streamlined and readable way to query collections of data. It integrates seamlessly with arrays, lists, XML, databases, and other collections, allowing developers to write expressive and concise code.
Similar to SQL syntax.
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
foreach (var num in evenNumbers)
{
Console.WriteLine(num); // Output: 2, 4
}
Uses extension methods.
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(num => num % 2 == 0);
foreach (var num in evenNumbers)
{
Console.WriteLine(num); // Output: 2, 4
}
Below is a table describing the most commonly used LINQ methods with examples and results:
Method | Description | Example | Result |
---|---|---|---|
Where | Filters a sequence | numbers.Where(num => num > 2) |
{ 3, 4, 5 } |
Select | Projects values | numbers.Select(num => num * 2) |
{ 2, 4, 6, 8, 10 } |
OrderBy | Sorts in ascending order | numbers.OrderBy(num => num) |
{ 1, 2, 3, 4, 5 } |
OrderByDescending | Sorts in descending order | numbers.OrderByDescending(num => num) |
{ 5, 4, 3, 2, 1 } |
First | Returns the first element | numbers.First() |
1 |
FirstOrDefault | Returns first element or default | numbers.FirstOrDefault(num => num > 5) |
0 (default for int) |
Sum | Calculates the sum of elements | numbers.Sum() |
Sum of numbers |
Max | Finds the maximum element | numbers.Max() |
Maximum value |
Min | Finds the minimum element | numbers.Min() |
Minimum value |
Average | Calculates the average | numbers.Average() |
Average value |
Count | Counts the number of elements | numbers.Count() |
Number of elements |
All | Checks if all elements satisfy a condition | numbers.All(num => num > 0) |
true |
Any | Checks if any element satisfies a condition | numbers.Any(num => num > 3) |
true |
Contains | Checks if a sequence contains an element | numbers.Contains(3) |
true |
Distinct | Removes duplicate elements | numbers.Distinct() |
{ 1, 2, 3, 4, 5 } |
Take | Takes the first N elements | numbers.Take(3) |
{ 1, 2, 3 } |
Skip | Skips the first N elements | numbers.Skip(3) |
{ 4, 5 } |
TakeWhile | Takes elements while a condition is true | numbers.TakeWhile(num => num < 3) |
{ 1, 2 } |
SkipWhile | Skips elements while a condition is true | numbers.SkipWhile(num => num < 3) |
{ 3, 4, 5 } |
GroupBy | Groups elements by a key | students.GroupBy(s => s.Gender) |
Groups by Male and Female
|
Join | Joins two collections | students.Join(products, s => s.Id, p => p.Id, (s, p) => new { s.Name, p.Name }) |
Joined results |
Aggregate | Performs a custom aggregation | numbers.Aggregate((sum, next) => sum + next) |
15 (sum of numbers) |
DefaultIfEmpty | Returns default value if sequence is empty | new List<int>().DefaultIfEmpty(-1) |
{-1} |
Reverse | Reverses the order of elements | numbers.Reverse() |
{ 5, 4, 3, 2, 1 } |
Intersect | Returns common elements between sequences | numbers1.Intersect(numbers2) |
Common elements in both collections |
Union | Returns unique elements from both sequences | numbers1.Union(numbers2) |
Unique elements combined from both |
Except | Returns elements not in the second sequence | numbers1.Except(numbers2) |
Elements in numbers1 but not in numbers2
|
ToDictionary | Converts a sequence into a dictionary | students.ToDictionary(s => s.Id, s => s.Name) |
{ 1: "John", 2: "Jane" } |
int[] numbers = { 1, 2, 3, 4, 5 };
var filteredNumbers = numbers
.Where(num => num > 2)
.OrderByDescending(num => num)
.Select(num => num * 2);
foreach (var num in filteredNumbers)
{
Console.WriteLine(num); // Output: 10, 8, 6
}
Let’s use the provided Student
and Product
classes to illustrate LINQ in action:
public void AdvancedExample()
{
var filteredStudents = students
.Where(s => s.Age > 20)
.OrderBy(s => s.Name)
.Select(s => new { s.Name, s.Age })
.ToList();
var groupedByGender = students
.GroupBy(s => s.Gender)
.Select(group => new { Gender = group.Key, Count = group.Count() })
.ToList();
var availableProducts = products
.Where(p => p.Stock > 0)
.OrderByDescending(p => p.Price)
.Take(3)
.ToList();
var studentExists = students.Any(s => s.Name == "Jane Smith");
var allAdults = students.All(s => s.Age >= 18);
var uniquePrices = products.Select(p => p.Price).Distinct().ToList();
}
- LINQ Basics: Provides a way to query and manipulate collections using both query and method syntax.
-
Comprehensive Methods: Methods like
Where
,Select
,OrderBy
,GroupBy
,Join
,Aggregate
, and more offer flexibility in handling collections. - Practical Use: Examples show how LINQ can simplify operations on both simple data types and objects.
LINQ in C# enhances code readability and efficiency, making data operations more intuitive and concise.
-
Introduction to C#
What is C#? -
Variables and Data Types
Understand how to declare and use variables. -
Operators
Arithmetic, relational, and logical operators in C#. -
Control Statements
If-else, switch, and looping constructs.
-
Classes and Objects
Basics of OOP in C#. -
Inheritance
How to use inheritance effectively. -
Polymorphism
Method overriding and overloading. -
Encapsulation
Understanding access modifiers.
-
LINQ Basics
Working with Language Integrated Query. -
Asynchronous Programming
Introduction to async/await. -
File Handling
Reading and writing files.
-
Number Formatting
Formatting numbers in C#. -
Exception Handling
Handling runtime errors effectively. -
Working with Dates
DateTime and time zone handling. -
Using Keyword in C#
Different usages of theusing
keyword in C#.
-
Setting Up Development Environment
Installing Visual Studio and .NET SDK. - Useful Libraries Libraries and tools for C# development.