LINQ: Zip() operator

zip() operator in

There is also a video version of this tutorial.

Let’s understand it with example.

int[] nums1 = [1, 2, 3, 4];
int[] nums2 = [3, 4, 5, 6];

IEnumerable<int>? product = nums1.Zip(nums2, (n1, n2) => n1 * n2);

Console.WriteLine(string.Join(", ", product));  // 3, 8, 15, 24

Let’s break it down:

IEnumerable<int>? product = nums1.Zip(nums2, (n1, n2) => n1 * n2);

It takes nums1[i] and nums2[i], evaluates it (nums1[0]*nums2[0]) and returns it. Here i is the index of the array. For example.

[Read More]

Curious Case of LINQ Group By

curious case of linq group by

Schema

  • Department (DepartmentId, Name)
  • Employee (EmployeeId, Name, DepartmentId)

Result set I need

Show all departments with total number of employees. Do not skip the departments which have 0 employees. As shown below:

DepartmentIdNameTotalEmployees1Engineering22Marketing13HR0

I have applied various queries and checked their equivalent sql.

1. Straightforward but skips the department which has no employees

This query does not meet my requirement. It would be a good choice if I don’t need departments without any employees.

[Read More]

LINQ: SelectMany()

select many operator in linq

NOTE: You can find the source code here.

Schema Overview

// Department
public class Department
{
    public int DepartmentId { get; set; }
    public string Name { get; set; } = string.Empty;

    public ICollection<Employee> Employees { get; set; } = [];
}

// Employee

public class Employee
{
    public int EmployeeId { get; set; }
    public string Name { get; set; } = string.Empty;

    public int DepartmentId { get; set; }

    public Department Department { get; set; } = null!;

    public ICollection<EmployeeSkill> EmployeeSkills { get; set; } = [];
}

// Skills

public class Skill
{
    public int SkillId { get; set; }
    public string Name { get; set; } = string.Empty;

    public ICollection<EmployeeSkill> EmployeeSkills { get; set; } = [];
}

// EmployeeSkills (Junction table)

public class EmployeeSkill
{
    public int EmployeeId { get; set; }
    public int SkillId { get; set; }

    public Employee Employee { get; set; } = null!;
    public Skill Skill { get; set; } = null!;
}

In simpler terms:

[Read More]

Higher Order Functions in C#

Higher-order functions (HOF) are functions that can take a function as an argument or return a function or both. In C#, higher-order functions are achieved using delegates, lambda expressions and expression trees.

Example 1: Using a Delegate

// Declare a delegate that takes an int and returns an int
public delegate int IntOperation(int x);

public class Program
{
    // Higher-order function that takes a delegate as an argument
    public static int PerformOperation(int value, IntOperation operation)
    {
    return operation(value);
    }

    public static void Main()
    {
        // Create a delegate instance that points to the Square method
        IntOperation square = x => x \* x;

        // Pass the delegate to the higher-order function
        int result = PerformOperation(5, square);
        Console.WriteLine(result); // Output: 25
    }

}

Example 2 : Using lambda expression

// Higher-order function that takes a lambda expression as an argument
public static int PerformOperation(int value, Func<int, int\> operation)
{
 return operation(value);
}

// main method

// Define a lambda expression that squares a number
Func<int, int> square = x => x * x;

// Pass the lambda expression to the higher-order function
int result = PerformOperation(5, square);

Example 3: Function as a Return Value

public class Program
{
    // Higher-order function that returns a function
    public static Func<int, int\> GetOperation(bool isSquare)
    {
        if (isSquare)
        {
            return x => x \* x;
        }
        else
        {
            return x => x + x;
        }
    }

    public static void Main()
    {
        // Get a function that squares a number
        Func<int, int> operation = GetOperation(true);

        // Use the returned function
        int result = operation(5);
        Console.WriteLine(result); // Output: 25
    }
}

In c#, higher order functions are everywhere. If one have used LINQ, must have used HO functions. Collection’s Where() is the good example.

[Read More]

Let's dive into various types of properties in c#

various types of properties in c#

I assume you have some knowledge of C# properties. If not, here’s a quick definition: A property is a class member that provides a flexible way to read, write, or compute the value of a private field. Don’t worry if you’re new to properties; we’ll be using them in this blog, and I’ll explain them as we go along.

1. Properties with getter and setter

public class Person
{
 public string Name { get;set; }
 public int Age { get; set;}
}

Generally, we define properties like this. The Person class has two properties Name and Age, each with getters and setters. This enables you to set and read their values.

[Read More]

Understanding The Pure And Impure Functions in C#

What is pure function in c#?

Pure functions

Pure function is that:

  1. Always returns the same output given the same inputs.
  2. Does not modify the state of object or any external state.
  3. Does not have any side effects such as I/O operations, exceptions or modifying external variables.
  • In other words, a pure function takes input, process it and returns the output without modifying anything else.
  • Pure functions are easy to test and debug.

Examples

  1. Mathematical calculations
public int Add(int a, int b)
{
 return a + b;
}
  1. String manipulation
public string Concatenate(string a, string b)
{
 return a + b;
}
  1. Array operations
public int[] SortArray(int[] array)
{
 return array.OrderBy(x => x).ToArray();
}
  1. Data transformations
public string ConvertToString(int value)
{
 return value.ToString();
}
  1. Validation
public bool IsValidEmail(string email)
{
 return email.Contains("@");
}

Impure Functions

Impure function is that

[Read More]

Private Constructor in C#

private constructor in c#

In C#, a private constructor is a constructor method declared with the private access modifier (or without mentioning any modifier). If a class have only a private constructor and does not have any public constructor, then you are not able to create the instance of a class. Example 👇

public class Student
{
 Student() { } // private constructor
}

public class Program
{
 static void Main()
 {
 Student stu = new(); //Error CS0122 'Student.Student()'
 // is inaccessible due to its protection level

    }

}

When you try to create the instance of stu, you will the following error.

[Read More]

Delegates, Anonymous Method and Lambda Expression

Delegates, anonymous method and lambda expression in c#

  • Delegates in C# are essentially type-safe function pointers.
  • They allow you to treat methods as objects, enabling you to pass methods as parameters, store them in variables, and invoke them dynamically.
  • Delegates are particularly useful for implementing callback mechanisms and event handling in C#.

delegate void MyDelegate(string message);

You can point this delegate to any method with similar signature.

namespace BasicsOfCSharp;

// Declare a delegate type
delegate void MyDelegate(string message);

class Program
{
 // Method that matches the delegate signature
 static void DisplayMessage(string message)
 {
 Console.WriteLine("Message: " + message);
 }
 static void Main()
 {
        // Instantiate the delegate.
        MyDelegate handler = DisplayMessage;

        // calling the handler
        handler("Hello..");

    }

}

👉Multicast Delegate:

[Read More]

Abstract Class in C#

In c#, Abstract class is a class that can not be instantiated on its own

abstract class in c#

  • In c#, Abstract class is a class that can not be instantiated on its own
  • It is typically used as a base class for other class.
  • Abstract class provides a way to achieve abstraction, because there you can just declare the methods (abstract methods) and implement them later.
  • It can contain both abstract methods (methods without implementation details) and non-abstract methods (method with implementation details).
  • Similar goal can be achieved with interface, but in abstract class you can also define non-abstract method. These methods are needed when you need to share some common functionality.
public abstract class Shape
{
 // it is the basic syntax of abstract class
}

Example:

[Read More]

Easiest Way to Handle Csv Files in Csharp

how to read and write to csv files in c#

In this tutorial we will se how to read and write data to csv file. It is pretty much easy if you have some external library for that. We are definitely going to use a library and that will be CsvHelper.

You can also check the video version of this tutorial.

First and foremost, create a c# console application in .net core. After that we need to install a nuget package, which is**CsvHelper**

[Read More]