OneBite.Dev - Coding blog in a bite size

Count The Number Of Occurrences Of A Specific Element In An Array In C#

Code snippet for how to Count The Number Of Occurrences Of A Specific Element In An Array In C# with sample and detail explanation

Counting the number of occurrences of a specific element in an array is a common problem in C#. This article will provide a simple code snippet for this purpose, and give a step-by-step explanation of how to implement this code.

Code Snippet

In a C# program, one could use a List to store the array, then make use of the ‘.Count’ function that is built into C#. This function will return the number of times the specified element appears in the List.

Here’s a simple C# code snippet to demonstrate this:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        //Defining an array
        int[] array = { 1, 2, 3, 2, 2, 3, 4, 2, 4, 5, 6, 4 };

        //Specifying the element to be counted
        int ElementToCount = 2;

        //Counting the number of occurrences of specified element
        int Occurrences = array.Count(element => element == ElementToCount);

        //Printing the total count
        Console.WriteLine("Number of times " + ElementToCount + " appears in array: " + Occurrences);
    }
}

When run, this program will print out the number of times number ‘2’ appears in the array.

Code Explanation

Here’s a step-by-step breakdown of how this code works:

  1. First, the array is defined. This array is named ‘array’ and contains the numbers 1, 2, 3, 2, 2, 3, 4, 2, 4, 5, 6, and 4.

  2. Then, the element to be counted is specified. The variable for this is named ‘ElementToCount’ and is set to ‘2’. Thus, the code will count the number of times ‘2’ appears in the array.

  3. Next, the ‘.Count’ function of the List method is used to count how many times ‘ElementToCount’ appears in ‘array’.

  4. Here’s the essential part of the line of code that does this: ‘array.Count(element => element == ElementToCount)‘. This command uses a lambda expression to compare each element in the array to ‘ElementToCount’. Whenever there’s a match, the count increases by 1.

  5. Lastly, the total count is printed to the console using ‘Console.WriteLine()‘. This will display the message ‘Number of times 2 appears in array: ’ followed by the actual count.

This is a simple and efficient method for counting occurrences of a specific element in an array in C#.

c-sharp