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

The following code snippets can be used to find the occurence of an element in an integer array.

static void Main(string[] args)
{
//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;
}

The following code snippets can be used to find the occurence of an element in a string array.

static void Main(string[] args)
{
//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;
}
}

I have posted this code snippet in dotnetspider.com. Click here to view it.

Advertisements

%d bloggers like this: