0
0
C Sharp (C#)programming~20 mins

Why LINQ depends on extension methods in C Sharp (C#) - See It in Action

Choose your learning style9 modes available
Why LINQ depends on extension methods
📖 Scenario: Imagine you have a list of numbers and you want to find all the even numbers easily. LINQ helps you do this in a simple way. Behind the scenes, LINQ uses something called extension methods to add new abilities to lists without changing their original code.
🎯 Goal: You will create a list of numbers, add an extension method to find even numbers, and then use it to get and print those even numbers.
📋 What You'll Learn
Create a list of integers called numbers with values 1, 2, 3, 4, 5, 6
Create a static class called MyExtensions with an extension method GetEvenNumbers for IEnumerable<int>
Use the extension method GetEvenNumbers on the numbers list to get even numbers
Print the even numbers separated by spaces
💡 Why This Matters
🌍 Real World
Extension methods let developers add useful features to existing classes without changing their code. This is how LINQ works to query collections easily.
💼 Career
Understanding extension methods is important for writing clean, reusable C# code and working with LINQ, which is widely used in software development.
Progress0 / 4 steps
1
Create the list of numbers
Create a list of integers called numbers with these exact values: 1, 2, 3, 4, 5, 6
C Sharp (C#)
Need a hint?

Use List<int> and initialize it with the values inside curly braces.

2
Create the extension method
Create a static class called MyExtensions and inside it create a public static extension method called GetEvenNumbers that takes this IEnumerable<int> source and returns only even numbers using a foreach loop and yield return
C Sharp (C#)
Need a hint?

Extension methods must be inside a static class and have this before the first parameter.

3
Use the extension method to get even numbers
Create a variable called evenNumbers and set it to the result of calling numbers.GetEvenNumbers()
C Sharp (C#)
Need a hint?

Call the extension method directly on the numbers list.

4
Print the even numbers
Use a foreach loop to print each number in evenNumbers separated by spaces on one line
C Sharp (C#)
Need a hint?

Use Console.Write inside the loop to print numbers on the same line separated by spaces.