Saturday, 16 November 2024

Coding Test: Extension method

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 and GetEvenNumbers methods are simple extension methods that work on any collection implementing IEnumerable<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

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives