LINQ in C#
# CHAPTER 21
LINQ in C#
1. Introduction
Imagine you have aList of 1,000 employees and you need to find all employees who work in the "IT" department, sorted alphabetically by their last name. In the old days, you'd have to write multiple foreach loops, if statements, and a custom sorting algorithm.
LINQ (Language-Integrated Query) revolutionizes this. Introduced in C# 3.0, it allows you to query collections (Lists, Arrays, Databases) using a clean, declarative syntax similar to SQL.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Include the
System.Linqnamespace.
-
Understand Lambda Expressions (
=>).
-
Filter data using
.Where().
-
Sort data using
.OrderBy().
-
Project data using
.Select().
3. Lambda Expressions (The Heart of LINQ)
Before using LINQ, you must understand Lambda expressions. They are a shorthand way to write a tiny inline function.Syntax: (parameters) => expression
*(Read the => symbol as "goes to").*
4. Filtering Data with .Where()
Let's filter an array of numbers to find only the even numbers.
*(Requires using System.Linq;)*
*Note: LINQ queries return IEnumerable<T>. We use .ToList() at the end to convert the result back into a standard List.*
5. Sorting Data with .OrderBy()
Sorting is incredibly easy with LINQ.
6. Projecting Data with .Select()
.Select() transforms the data. Imagine you have a List of complex User objects, but you only want a simple List of their email addresses.
7. Chaining LINQ Methods
The true power of LINQ is that you can chain these methods together like a pipeline.8. Common Mistakes
-
Deferred Execution: A LINQ query is NOT actually executed when you define it. It only executes when you iterate over it (e.g., in a
foreachloop) or call a materialization method like.ToList(). If you modify the original list before calling.ToList(), the LINQ query will reflect the modified data! Always append.ToList()if you want to snapshot the data immediately.
-
Forgetting
using System.Linq;: If you try to call.Where()and get an error saying the method doesn't exist, you forgot the using directive at the top of the file.
9. Best Practices
-
Prefer LINQ over standard
forloops when filtering and sorting data. It makes the code instantly readable.
-
Be careful with
.ToList()inside loops. Calling.ToList()allocates new memory on the Heap. Doing it too often can cause performance issues.
10. Exercises
-
1.
Create a
List<int>with numbers 1 to 20. Use LINQ to find all numbers greater than 10, then sort them descending.
-
2.
Create a
List<string>of 5 animal names. Use.Where()to find all names that contain the letter "a".
11. MCQs with Answers
What does LINQ stand for?
Which namespace is required to use LINQ?
What is the => symbol called in C#?
Which LINQ method is used to filter data based on a condition?
Which LINQ method is used to sort data in ascending order?
Which LINQ method is used to extract a specific property from a list of objects?
What does .ToList() do at the end of a LINQ query?
What happens if you define a LINQ query but never call .ToList() or iterate over it?
.Where().OrderBy())?
a) Yes b) No
Answer: a) Yes
What is the main advantage of LINQ?
12. Interview Questions
- Q: Explain Deferred Execution in LINQ. Why is it useful?
-
Q: What is the difference between
.FirstOrDefault()and.SingleOrDefault()? (Answer: FirstOrDefault returns the first match or null; SingleOrDefault returns the match, but throws an exception if *more than one* match exists).
13. Summary
LINQ brings the power of database querying directly into C#. Using Lambda expressions, you can filter (.Where), sort (.OrderBy), and transform (.Select) any C# collection with minimal code. It is an indispensable tool in modern .NET development.