Create an extension method to filter out odd and even numbers from a collection like a list or array. Below is an example of how you can write such extension methods.
1. Extension Method to Filter Odd Numbers
This method filters odd numbers from a collection of integers.
using System;
using System.Collections.Generic;
public static class NumberExtensions
{
// Extension method to get odd numbers from an IEnumerable<int>
public static IEnumerable<int> GetOddNumbers(this IEnumerable<int> numbers)
{
foreach (var number in numbers)
{
if (number % 2 != 0)
{
yield return number;
}
}
}
// Extension method to get even numbers from an IEnumerable<int>
public static IEnumerable<int> GetEvenNumbers(this IEnumerable<int> numbers)
{
foreach (var number in numbers)
{
if (number % 2 == 0)
{
yield return number;
}
}
}
}
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Filter odd numbers using extension method
var oddNumbers = numbers.GetOddNumbers();
Console.WriteLine("Odd Numbers:");
foreach (var number in oddNumbers)
{
Console.WriteLine(number);
}
// Filter even numbers using extension method
var evenNumbers = numbers.GetEvenNumbers();
Console.WriteLine("Even Numbers:");
foreach (var number in evenNumbers)
{
Console.WriteLine(number);
}
}
}
Output:
Odd Numbers: 1 3 5 7 9 Even Numbers: 2 4 6 8 10
Summary:
- The
GetOddNumbers
andGetEvenNumbers
methods are simple extension methods that work on any collection implementingIEnumerable<int>
. yield return
is used in the methods to lazily return the filtered numbers without creating a new list upfront, making it memory efficient.
0 comments:
Post a Comment