Hello, I'm

Vijay Sharma

I'm a Full Stack Web Developer

An enthusiastic person currently shaping the future of software development by designing and developing smooth user interfaces that promote user interaction with information and data.

About Me

C# tutorial for beginners 🎮


C# | tutorial for beginners 🎮

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // This is the starting point of our program.
            // It's where the program begins to run.

            // The following lines of code display messages on the screen.
            // We use the "Console.WriteLine" method to do this.

            // This line says, "Print 'I like pizza!' on the screen."
            Console.WriteLine("I like pizza!");

            // This line says, "Print 'It's really good!' on the screen."
            // Notice that we use double quotation marks to include the ' character.
            Console.WriteLine("It's really good!");

            // The program will stop running after these lines are executed.
        }
    }
}


C# | Output 💬

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // The "Main" method is the starting point of our program.

            // Console.Write("Hey!"); prints "Hey!" without moving to the next line.
            Console.Write("Hey!");

            // Console.WriteLine("Hello!"); prints "Hello!" and moves to the next line.
            Console.WriteLine("Hello!");

            // This is a single-line comment. Comments are ignored by the program and are used for explanations.

            /*
             * This is a multiline comment.
             * You can write multiple lines of comments like this.
             * It's useful for providing detailed explanations.
             */

            // Console.WriteLine("Club of Developers"); prints "Club of Developers" and moves to the next line.
            Console.WriteLine("Club of Developers");

            // Console.ReadKey() waits for a key press before the program exits.
            Console.ReadKey();
        }
    }
}

C# | Variables ✖️

Code provides a basic introduction to C# programming concepts. Here's a brief explanation of the code for beginners:

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Declaration of variables
            int x; // This declares an integer variable named 'x'
            
            // Initialization of variables
            x = 123; // 'x' is assigned the value 123

            // Declaration and initialization in one step
            int y = 321; // This declares an integer variable 'y' and assigns it the value 321

            // Performing arithmetic operations
            int z = x + y; // 'z' is the result of adding 'x' and 'y'

            // Different data types
            int age = 21; // An integer variable to store a whole number
            double height = 300.5; // A double variable to store a decimal number
            bool alive = false; // A bool variable to store true or false
            char symbol = '@'; // A char variable to store a single character
            string name = "Bro"; // A string variable to store a series of characters

            // Displaying information using Console.WriteLine
            Console.WriteLine("Hello " + name); // Concatenating strings and variables
            Console.WriteLine("Your age is " + age);
            Console.WriteLine("Your height is " + height + "cm"); // Concatenating with a string
            Console.WriteLine("Are you alive? " + alive);
            Console.WriteLine("Your symbol is: " + symbol);

            // Combining variables to create a new one
            string userName = symbol + name; // Concatenating 'symbol' and 'name' to create a new string

            Console.WriteLine("Your username is: " + userName);

            // Waiting for user input to keep the console window open
            Console.ReadKey();
        }
    }
}

C# | Constants π

Code demonstrates the usage of constants in C#. Here's a brief explanation of the code for beginners:

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Constants are immutable values that are known at compile time and do not change during the program's execution.

            const double pi = 3.14; // Declares a constant 'pi' with a value of 3.14

            // Attempting to change a constant will result in a compilation error.
            // Uncommenting the line below will result in an error:
            // pi = 420; // You can't change the value of a constant

            Console.WriteLine(pi); // Outputs the value of the 'pi' constant

            // Waiting for user input to keep the console window open
            Console.ReadKey();
        }
    }
}


C# | type casting 💱

Our code illustrates the concept of type casting in C#, where you convert values between different data types. Here's a brief explanation for beginners:

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Type casting is the process of converting a value from one data type to another.
            // This is useful when you need to work with different data types or convert user input.

            double a = 3.14; // A double with the value 3.14
            int b = Convert.ToInt32(a); // Convert the double 'a' to an integer 'b'

            int c = 123; // An integer with the value 123
            double d = Convert.ToDouble(c); // Convert the integer 'c' to a double 'd'

            int e = 321; // An integer with the value 321
            string f = Convert.ToString(e); // Convert the integer 'e' to a string 'f'

            string g = "$"; // A string with the value "$"
            char h = Convert.ToChar(g); // Convert the string 'g' to a character 'h'

            string i = "true"; // A string with the value "true"
            bool j = Convert.ToBoolean(i); // Convert the string 'i' to a boolean 'j'

            // Display the data types of the converted variables
            Console.WriteLine(b.GetType()); // Outputs the type of 'b'
            Console.WriteLine(d.GetType()); // Outputs the type of 'd'
            Console.WriteLine(f.GetType()); // Outputs the type of 'f'
            Console.WriteLine(h.GetType()); // Outputs the type of 'h'
            Console.WriteLine(j.GetType()); // Outputs the type of 'j'

            // Waiting for user input to keep the console window open
            Console.ReadKey();
        }
    }
}


C# | User Input ⌨️

Your code prompts the user to enter their name and age, then displays a greeting message along with their age. Here's a brief explanation of the code for beginners:

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Prompt the user to enter their name and age
            Console.WriteLine("What's your name?");
            String name = Console.ReadLine(); // Read the user's name as a string

            Console.WriteLine("What's your age?");
            int age = Convert.ToInt32(Console.ReadLine()); // Read the user's age as a string and convert it to an integer

            // Display a personalized greeting
            Console.WriteLine("Hello " + name); // Greet the user by name
            Console.WriteLine("You are " + age + " years old"); // Display the user's age

            // Waiting for user input to keep the console window open
            Console.ReadKey();
        }
    }
}


C# | Arithmetic Operators 🧮

Below code demonstrates basic arithmetic operations and increment / decrement operations in C#. Here's a brief explanation for beginners:

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            int friends = 5; // Declare and initialize a variable 'friends' with the value 5

            friends = friends + 1; // Increment 'friends' by 1
            // You can achieve the same result using these shortcuts:
            // friends += 1; // Increment 'friends' by 1
            // friends++; // Increment 'friends' by 1

            // If you want to decrement the value, you can do:
            // friends = friends - 1; // Decrement 'friends' by 1
            // friends -= 1; // Decrement 'friends' by 1
            // friends--; // Decrement 'friends' by 1

            // You can perform other arithmetic operations in a similar way:
            // friends = friends * 2; // Multiply 'friends' by 2
            // friends *= 2; // Multiply 'friends' by 2
            // friends = friends / 2; // Divide 'friends' by 2
            // friends /= 2; // Divide 'friends' by 2

            // You can also calculate the remainder of a division using the modulus operator '%':
            // int remainder = friends % 2; // Calculate the remainder when 'friends' is divided by 2

            Console.WriteLine(friends); // Output the value of 'friends'

            // Waiting for user input to keep the console window open
            Console.ReadKey();
        }
    }
}


C# | Math class 📏

Below code demonstrates the usage of various mathematical functions available in the Math class in C#. Here's a brief explanation for beginners

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Declare and initialize two double variables
            double x = 3;
            double y = 5;

            // Calculate the square of 'x' using Math.Pow
            double a = Math.Pow(x, 2); // Result: 9.0

            // Calculate the square root of 'x' using Math.Sqrt
            double b = Math.Sqrt(x); // Result: 1.732...

            // Calculate the absolute value of 'x' using Math.Abs
            double c = Math.Abs(x); // Result: 3.0

            // Round 'x' to the nearest integer using Math.Round
            double d = Math.Round(x); // Result: 3.0

            // Round 'x' up to the nearest integer using Math.Ceiling
            double e = Math.Ceiling(x); // Result: 3.0

            // Round 'x' down to the nearest integer using Math.Floor
            double f = Math.Floor(x); // Result: 3.0

            // Find the maximum value between 'x' and 'y' using Math.Max
            double g = Math.Max(x, y); // Result: 5.0

            // Find the minimum value between 'x' and 'y' using Math.Min
            double h = Math.Min(x, y); // Result: 3.0

            // Output the result of the calculations
            Console.WriteLine(a); // Outputs 9.0

            // Waiting for user input to keep the console window open
            Console.ReadKey();
        }
    }
}


C# | Random numbers 🎲

Below code uses the Random class to generate random numbers in C#. Here's a brief explanation for beginners:

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Random class to generate random numbers
            Random random = new Random();

            // Generate random integers between 1 and 6 (inclusive) for three variables
            int num1 = random.Next(1, 7); // Result: Random number between 1 and 6
            int num2 = random.Next(1, 7); // Result: Random number between 1 and 6
            int num3 = random.Next(1, 7); // Result: Random number between 1 and 6

            // Generate a random double between 0.0 (inclusive) and 1.0 (exclusive)
            // double num = random.NextDouble();

            // Output the generated random numbers
            Console.WriteLine(num1);
            Console.WriteLine(num2);
            Console.WriteLine(num3);

            // Waiting for user input to keep the console window open
            Console.ReadKey();
        }
    }
}


C# | hypotenuse calculator program 📐

Below code calculates the length of the hypotenuse of a right triangle using the Pythagorean theorem. Here's a brief explanation for beginners

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Prompt the user to enter the lengths of sides A and B
            Console.WriteLine("Enter side A: ");
            double a = Convert.ToDouble(Console.ReadLine()); // Read side A as a double

            Console.WriteLine("Enter side B: ");
            double b = Convert.ToDouble(Console.ReadLine()); // Read side B as a double

            // Calculate the length of the hypotenuse (side C) using the Pythagorean theorem
            double c = Math.Sqrt((a * a) + (b * b)); // Calculate the square root of (a^2 + b^2)

            // Display the calculated hypotenuse
            Console.WriteLine("The hypotenuse is: " + c);

            // Waiting for user input to keep the console window open
            Console.ReadKey();
        }
    }
}


C# | string methods 🔤

Our code demonstrates various string manipulation operations in C#. Here's a brief explanation for beginners:

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Declare and initialize two strings
            string fullName = "Bro Code";
            string phoneNumber = "123-456-7890";

            // Convert the string to uppercase
            // fullName = fullName.ToUpper(); // Result: "BRO CODE"

            // Convert the string to lowercase
            // fullName = fullName.ToLower(); // Result: "bro code"

            // Replace dashes in the phone number with empty strings
            // phoneNumber = phoneNumber.Replace("-", ""); // Result: "1234567890"

            // Insert "Mr." at the beginning of the full name
            // string userName = fullName.Insert(0, "Mr."); // Result: "Mr. Bro Code"

            // Get the length (number of characters) of the full name
            // int fullNameLength = fullName.Length; // Result: 8

            // Extract the first name and last name using substring
            string firstName = fullName.Substring(0, 3); // Result: "Bro"
            string lastName = fullName.Substring(4, 4);  // Result: "Code"

            // Output the results of string manipulation
            Console.WriteLine(firstName); // Outputs "Bro"
            Console.WriteLine(lastName);  // Outputs "Code"

            // Waiting for user input to keep the console window open
            Console.ReadKey();
        }
    }
}


Number guessing game 🎮

C# program that generates a random number guessing game:

using System;

namespace NumberGuessingGame
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to the Number Guessing Game!");
            
            // Generate a random number between 1 and 100
            Random random = new Random();
            int randomNumber = random.Next(1, 101);
            
            int attempts = 0;
            bool guessedCorrectly = false;

            while (!guessedCorrectly)
            {
                Console.Write("Guess the number (1-100): ");
                int userGuess = int.Parse(Console.ReadLine());
                attempts++;

                if (userGuess == randomNumber)
                {
                    guessedCorrectly = true;
                    Console.WriteLine($"Congratulations! You guessed the number {randomNumber} in {attempts} attempts.");
                }
                else if (userGuess < randomNumber)
                {
                    Console.WriteLine("Try a higher number.");
                }
                else
                {
                    Console.WriteLine("Try a lower number.");
                }
            }

            Console.WriteLine("Thanks for playing!");

            // Waiting for user input to keep the console window open
            Console.ReadKey();
        }
    }
}


// In this program:

// The user is welcomed to the Number Guessing Game.
// A random number between 1 and 100 is generated.
// The program enters a loop where the user is asked to guess the number.
// The program provides feedback if the guessed number is too high or too low.
// Once the user guesses the correct number, the program congratulates them and shows the number of attempts.
// The program waits for user input to keep the console window open after the game is finished.
// It's a simple and engaging game that allows users to test their guessing skills.


C# | Exception Handling 🚨

Below provided C# code defines a simple program that demonstrates exception handling. Here's an explanation of how the code works:

namespace Program
{
    public class Program
    {
        public static void Main()
        {
            try
            {
                // Prompt the user to enter an integer (for example, 5)
                int index = Convert.ToInt32(Console.ReadLine()); // Input: 5

                // Call BaseMethod with the provided index and display the result
                Console.WriteLine(BaseMethod(index)); // Outputs the value from BaseMethod
            }
            catch (Exception ex)
            {
                // Handle any exceptions that occur
                Console.WriteLine(ex.Message); // Output the exception message
                Console.WriteLine(ex.StackTrace); // Output the stack trace for debugging
            }

            Console.ReadLine(); // Wait for user input before closing the console
        }

        public static int BaseMethod(int index)
        {
            // Call ChildMethod with the provided index
            return ChildMethod(index);
        }

        public static int ChildMethod(int index)
        {
            // Define an integer array with values {1, 2, 3, 4, 5}
            int[] arr = { 1, 2, 3, 4, 5 };

            // Attempt to access an element in the array with the provided index
            return arr[index];
        }
    }
}



// Input : 5
// Output : 
Index was outside the bounds of the array.
   at Program.Program.ChildMethod(Int32 index) in C:\Users\Vijay Sharma\source\repos\PracticeC#\PracticeC#\Program.cs:line 319
   at Program.Program.BaseMethod(Int32 index) in C:\Users\Vijay Sharma\source\repos\PracticeC#\PracticeC#\Program.cs:line 314
   at Program.Program.Main() in C:\Users\Vijay Sharma\source\repos\PracticeC#\PracticeC#\Program.cs:line 302

C# | File Handling 📁

Here's an explanation of your C# code that lists and prints directories within a specified root path :

This C# program is designed to list and print the names of directories within a specified root path. Here's a brief explanation of what the program does:

using System;         // Import the System namespace
using System.IO;      // Import the necessary using directive for System.IO

namespace FileHandlingPractice
{
    class Program
    {
        static void Main()
        {
            // Define the root directory path you want to work with
            string rootPath = "D:\\FileHandlingPractice";

            // Use Directory.EnumerateDirectories to retrieve a collection of directory paths
            var directories = Directory.EnumerateDirectories(rootPath);

            // Iterate through the collection of directory paths
            foreach (var directory in directories)
            {
                // Print each directory path to the console
                Console.WriteLine(directory);
            }
        }
    }
}


// Output :
// D:\FileHandlingPractice\SubFolder1
// D:\FileHandlingPractice\SubFolder2

C# - Switches

// Switch Statement
// Switch is an alternative to many "else if" statement !

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("What day is it today ?");
        string? day = Console.ReadLine();
        
        switch (day)
        {
            case "Monday":
                Console.WriteLine("It's Monday !");
                break;
            case "Tuesday":
                Console.WriteLine("It's Tuesday !");
                break;
            case "Wednesday":
                Console.WriteLine("It's Wednesday !");
                break;
            case "Thursday":
                Console.WriteLine("It's Thursday !");
                break;
            case "Friday":
                Console.WriteLine("It's Friday !");
                break;
            case "Saturday":
                Console.WriteLine("It's Saturday !");
                break;
            case "Sunday":
                Console.WriteLine("It's Sunday !");
                break;
            default:
                Console.WriteLine(day + " is not a day !");
                break;
        }

        Console.ReadKey();
    }
}


Pythagorean theorem with C#

The hypatenuse squared is equals to the sum of sides square.

// Let's move into deep dive...

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Enter side a : ");
        double a = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("Enter side b : ");
        double b = Convert.ToDouble(Console.ReadLine());

        double c = Math.Sqrt((a * a) + (b * b));
        Console.WriteLine("The hypotenuse is : " + c);

        Console.ReadKey();
    }
}

// Input 1 :
// Enter side a : 3

// Input 2 :
// Enter side b : 4

// Output :
// The hypotenuse is : 5

How to genearate random number in c#

Let's move into deep dive...

// First we create the Program Class
class Program
{
    public static void Main(string[] args)
    {
    	// Create Object of Random class
        Random random = new Random();

        // Returns a non-negative random integer.
        // A 32 - bit signed integer that is greater than or equal to 0 and less than "int.MaxValue".
        int num1 = random.Next(); // Output : 1046318339

        // The exclusive upper bound of the random number to be generated must be greater than or equal to 0.
        // Return a 32-bit signed integer that is greater than or equal to 0, and less than maxValue.
        // However, if maxValue equals 0, maxValue is returned.
        int num2 = random.Next(7); // Output : 4

        // Return a 32-bit signed integer that is greater than or equal to minValue and less than maxValue.
        int num3 = random.Next(3,7); // Output : 6

        Console.WriteLine(num1);
        Console.WriteLine(num2);
        Console.WriteLine(num3);

        Console.ReadKey();
    }
}

// Output :
1046318339
4
6

C# String methods

Let's move into deep dive...

// Replace(oldValue, newValue) method
// All occurance of "oldValue" replaced with the "newValue".

class Program 
{
    public static void Main(string[] args)
    {
        string fullName = "Club of Developers";
        string phoneNumber = "123-456-7890";

        string newPhoneNum = phoneNumber.Replace("-", "/");
        Console.WriteLine(newPhoneNum);

        Console.ReadKey();
    }
}

// Output :
123/456/7890

Substring()

// Substring(startIndex)
// Substring(startIndex, length)

class Program
{
    public static void Main(string[] args)
    {
        string fullName = "Club of Developers";

        string subStr1 = fullName.Substring(8); // Output : Developers
        string subStr2 = fullName.Substring(8, 3); // Output : Dev

        Console.WriteLine(subStr1);
        Console.WriteLine(subStr2);

        Console.ReadKey();
    }
}

StartsWith() methods

Let's move into deep dive...

// StartsWith(charValue)
// StartsWith(stringValue)

class Program
{
    public static void Main(string[] args)
    {
        string fullName = "Club of Developers";

        // Taking "char" as an argument
        Console.WriteLine(fullName.StartsWith('C')); // True
        Console.WriteLine(fullName.StartsWith('D')); // False

        // Taking "string" as an argument
        Console.WriteLine(fullName.StartsWith("Club")); // True

        Console.ReadKey();
    }
}

// Output :
Return true if the value matches beginning of the string, otherwise return false.

ToLower() methods

// ToLower()
class Program
{
    public static void Main(string[] args)
    {
        string fullName = "Club of Developers";
        Console.WriteLine(fullName.ToLower());

        Console.ReadKey();
    }
}

// Output :
Return a copy of the string which will be converted into lowercase.

C# enums tutorial example explained

  • Enums are a powerful feature in C# that allow you to define a set of named integer constants.
  • They are particularly useful when you have a finite set of values that are not expected to change.
  • Enums provide a way to give meaningful names to integral values, making your code more readable and maintainable.
  • // To access the underlying integer value associated with an enum item, you can explicitly convert it to an int.
    
    // Example:
    // Planets is an enum containing the names of celestial bodies, with associated integer values.
    // To get the integer value of Planets.Mercury, you can do:
    // int mercuryValue = (int)Planets.Mercury;
    
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine(Planets.Mercury + " is planet #" + (int)Planets.Mercury);
            //Console.WriteLine(Planets.Pluto + " is planet #" + (int)Planets.Pluto);
    
            String name = PlanetRadius.Earth.ToString();
            int radius = (int)PlanetRadius.Earth;
            double volume = Volume(PlanetRadius.Earth);
    
            Console.WriteLine("planet: " + name);
            Console.WriteLine("radius: " + radius + "km");
            Console.WriteLine("volume: " + volume + "km^3");
    
            Console.ReadKey();
        }
        public static double Volume(PlanetRadius radius)
        {
            double volume = (4.0 / 3.0) * Math.PI * Math.Pow((int)radius, 3);
            return volume;
        }
    }
    enum Planets
    {
        Mercury = 1,
        Venus = 2,
        Earth = 3,
        Mars = 4,
        Jupiter = 5,
        Saturn = 6,
        Uranus = 7,
        Neptune = 8,
        Pluto = 9
    }
    
    enum PlanetRadius
    {
        Mercury = 2439,
        Venus = 6051,
        Earth = 6371,
        Mars = 3389,
        Jupiter = 69911,
        Saturn = 58232,
        Uranus = 25362,
        Neptune = 24622,
        Pluto = 1188
    }
    
    // Output :
    planet: Earth
    radius: 6371km
    volume: 1083206916845.7535km^3
    
    String collection

    The below code provided is a C# program that defines a list of strings and uses LINQ to filter out the strings that contain the substring "turorial". Here's my interpretation of the code:


    Explanation-->
      • Here's an explanation of the code var result = stringList.Where(s => s.Contains("turorial"));
      • `stringList` is a list of strings containing several items.
      • `.Where()` is an extension method provided by LINQ that allows you to filter a list based on a condition.
      • `s => s.Contains("turorial")` is a lambda expression that defines the condition for the filter. It takes an input parameters and returns a boolean value that indicates whether the input string contains the substring "turorial".
      • `var result` declares a new variable called `result` and assigns it the filtered list of strings as its value.

    So, the code above filters the stringList to include only the strings that contain the substring "turorial", and stores the filtered result in the result variable. In other words, the result variable will contain a list of all the strings in stringList that have the substring "turorial" in them.


    LinQ - In C#

    Let's have an another example...

    Explanation-->
      • The `Colleague` class is a template for creating objects that represent colleagues in an organization. It has several properties that store information about a colleague, such as their name, favorite quote, favorite food, etc.
      • You can create an object of this class for each colleague and store them in list or array for easy access and manipulation of the data.
      • In the above `Colleague` class, we have added several properties for each colleague, including Name, FavoriteQuote, FavoriteFood, Hobby, FavoriteMovie, Superpower, FavoriteAnimal, and FunFact.

    We can now create a list of Colleague objects and add multiple details for each colleague like this :
    
    List colleagues = new List
    {
        new Colleague 
        {
            Name = "Ankit Sir", 
            FavoriteQuote = "The best way to predict the future is to invent it.", 
            FavoriteFood = "Pizza",
            Age = 25,
            YearsOfExperience = 2
        },
        new Colleague 
        {
            Name = "Paaji", 
            FavoriteFood = "Rajma Chawal", 
            Hobby = "Playing Cricket",
            Age = 27,
            YearsOfExperience = 2
        },
        new Colleague 
        {
            Name = "Preeti Ma'am", 
            FavoriteMovie = "The Shawshank Redemption", 
            FavoriteAnimal = "Dogs",
            Age = 23,
            YearsOfExperience = 1
        },
        new Colleague 
        {
            Name = "Karan Sir", 
            FavoriteQuote = "I don't always write code, but when I do, I prefer C#.", 
            Superpower = "Ability to code without any bugs",
            Age = 22,
            YearsOfExperience = 2
        },
        new Colleague 
        {
            Name = "Manoj Sir", 
            FavoriteAnimal = "Pumba", 
            FunFact = "Able to eat anything like a pro",
            Age = 24,
            YearsOfExperience = 1
        },
        new Colleague 
        {
            Name = "Sakshi", 
            Hobby = "Painting", 
            FavoriteMovie = "The Godfather",
            Age = 26,
            YearsOfExperience = 1
        },
        new Colleague 
        {
            Name = "Minal", 
            FavoriteQuote = "Stay Hungry, Stay Foolish", 
            Superpower = "Invisibility",
            Age = 23,
            YearsOfExperience = 1
        }
    };
    
    var result = colleagues.Where(s => s.Age >= 25 && s.YearsOfExperience >= 2);
    
                
                
    Explanation-->
      • The above line is using LINQ to query a list of Colleague objects named colleagues. The Where method is used to filter the list based on a given condition. In this case, the condition is that the Age property of the Colleague object should be greater than or equal to 25 and the YearsOfExperience property should be greater than or equal to 2.
      • The Where method returns an IEnumerable <Colleague> collection containing all the Colleague objects that meet the specified condition. This collection is assigned to the result variable using the var keyword, which allows C# to infer the type of the variable based on the type of the object being assigned to it.

    Another Example
    Explanation-->
      • The code creates a new variable result that stores a filtered list of colleagues based on a condition specified using the LINQ Where method.
      • The condition is defined using a lambda expression that takes two parameters: value and index. The value parameter represents the current element in the colleagues list, and the index parameter represents the index of that element.
      • In the lambda expression, the Where method uses the index parameter to check if the index is even (index % 2 == 0). If the index is even, the lambda expression returns true, which includes the current element in the filtered list. If the index is odd, the lambda expression returns false, which excludes the current element from the filtered list.
      • In the lambda expression, the Where method uses the index parameter to check if the index is even (index % 2 == 0). If the index is even, the lambda expression returns true, which includes the current element in the filtered list. If the index is odd, the lambda expression returns false, which excludes the current element from the filtered list.

        So, the resulting `result` variable will contain a filtered list of colleagues, where only elements with even indices are included.


    Another ways to do the same thing :
    Explanation-->

    The above code is using LINQ syntax to filter the colleagues list and select those colleagues who have YearsOfExperience equals to 1, and the filtered result is stored in the result variable.

      • The from keyword starts the LINQ query by specifying the data source. In this case, it's the colleagues list.
      • The where keyword is used to filter the data source based on a specified condition. In this case, we are selecting only those colleagues whose YearsOfExperience is equal to 1.
      • The select keyword is used to project the filtered data into a new form. In this case, we are selecting the entire std object.

        After getting the filtered result, we can use the foreach loop to print each item in the result variable.


    Function with parameter

    The below code is using LINQ syntax to filter a collection of colleagues based on a specific condition, where the age of the colleague is between 23 and 26.

    
    var filterResult = from item in colleagues
                               where IsTeeAger(item)
                               select item;
    public static bool IsTeeAger(Colleague colleague)
    {
    	return colleague.Age > 23 && colleague.Age < 26;
    }
    
    

    Here's a breakdown of the code in a step-by-step format :-
      • Create a new variable called filterResult to hold the filtered collection.
      • Use the from keyword to specify the collection to be filtered, which is the colleagues collection.
      • Use the where keyword to specify the condition that each item in the collection must satisfy.
      • Call the IsTeeAger method to determine if the current colleague's age is between 23 and 26.
      • Use the select keyword to specify the result to be included in the filterResult collection.
      • Include the item in the select clause to ensure that the filtered collection contains only the items that meet the specified condition.
      • The IsTeeAger method is defined separately as a static method that takes a Colleague object as input and


    OfType() in - Query Syntax

    The below code demonstrates the usage of the OfType() method in LINQ to filter elements of a certain type from a mixed list. Here's what the code does:

    
    public class Student
    {
    	public int StudentId { get; set; }
    	public string StudentName { get; set; }
    }
    
    public static void Main()
    {
    	IList mixedList = new ArrayList()
    	{
    		1,"One","Two",32.2,
    		new Student() { StudentId = 1,StudentName = "John"}
    	};
    
    	var stringResult = from std in mixedList.OfType()
                           select std;
    }
    
    

    Here's a breakdown of the code in a step-by-step format :-
      • The code creates a mixed list called mixedList that contains elements of different types, such as `int`, `string`, `double`, and `Student`.
      • The OfType() method is used in a LINQ query to filter the elements of the mixed list that are of type string. The LINQ query uses the from and select clauses to project the filtered elements of the mixed list into a new collection called stringResult.
      • The OfType() method is a LINQ extension method that filters the elements of a collection based on a specified type. In this case, it filters the elements of the mixed list that are of type `string`.
      • The stringResult collection contains only the elements of the mixed list that are of type string.
      • Note that the OfType() method returns an IEnumerable<TSource> sequence of the specified type, which can be further processed or used in other parts of the code.


    Post a Comment

    0 Comments