Hi all...could anyone please tell me how when working with arrays you could use a forach loop to output the number of a certain item...

for instance...if i wanted to find out the number of 5's in an array...could i use a foreach loop to find that out?

Thanks

Recommended Answers

All 3 Replies

int numberOfFives = 0;
foreach (int i in myIntArray) {
    if (i == 5) {
        numberOfFives++;
    }
}

Console.WriteLine("There are {0} fives in the array", numberOfFives);

Hi all...could anyone please tell me how when working with arrays you could use a forach loop to output the number of a certain item...

for instance...if i wanted to find out the number of 5's in an array...could i use a foreach loop to find that out?

Thanks

public void ForTheNoob()
{
    int numOfFives = 0;
    int[] array = { 55, 15, 5, 10, 25, 5, 15, 5, 55 };

    foreach (int number in array)
    {
        if (number.Equals(5))
        {
            numOfFives++;
        }
    }

    Console.WriteLine("..there are {0} fives in the array", numOfFives);
}

There is a cooler, and faster, way to accomplish this.

List<int> myInts = new List<int>();

//add the ints
myInts.Add(5);
myInts.Add(50);
myInts.Add(15);
...

List<int> foundInts = myInts.FindAll((delegate(SearchInt int)
            {
                 return SearchInt == 5;
            });

Does basically the same as the examples for the foreach given. If you really have to use the foreach method

List<int> myInts = new List<int>();
int countOfFives = 0;
//add the ints
myInts.Add(5);
myInts.Add(50);
myInts.Add(15);
...

foreach(int myInt in myInts)
{
  if(myInt == 5)
     countOfFives++;
}

Use generics, they will make your professional life easier :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.