Finding the number of occurrences of an element in an array in .NET

Hi,
I will describe how to find the number of occurrences of an element in an array in .NET

The following code snippets help to find the number of occurrences of an element in an integer array.


//Declare an integer array
int[] integerArray = new int[] { 1, 2, 3, 1, 4, 5, 6, 1, 7, 8, 9, 1, 10, 11 };

//Find the occurence of the element '1' in the above array. The function 'CheckInteger' iterate through the array and compare each element of the array with '1'.
Console.WriteLine("No of occurrences for '1' : {0}", Array.FindAll(integerArray, CheckInteger).Length);

//This function loop through the array element when used in the Array.FindAll function
private bool CheckInteger(int n)
{
if (n == 1)
return true;
else
return false;

}


//Declare a string array
string[] stringArray = new string[] { "Chennai", "Delhi", "Bangalore", "Chennai", "Hydrabad", "Mumbai", "Kolkatta" };

//Find the occurence of the string ‘Chennai’ in the above array. The function ‘CheckForChennai’ iterate through the array and compare each element of the array with 'Chennai'.
Console.WriteLine("No of occurrences for 'Chennai' : {0}", Array.FindAll(stringArray, CheckForChennai).Length);


//This function loop through the array element when used in the Array.FindAll function
private bool CheckForChennai(string s)
{

if(s.ToLower() == "chennai")
{
return true;
}
else
{
return false;
}
}


The output will be :
No of occurrences for '1' : 4
No of occurrences for 'Chennai' : 2


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: