0

I have an int array that store age values. I want to print all the values in the array which are above or eqaul to 18.

int[] age = new int[] { 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 };
      
foreach(int item in age)
{

}

I tried something like this but didn't work.

int[] age = new int[] { 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 };
int targetAge = 18;
int findedAge = Array.FindIndex(age, age => age == targetAge);

if (age>= targetAge)
{
    foreach (int item in age)
    {
        Console.WriteLine(item);
    }
}
1
  • FindIndex returns the index of the first element that's equal to targetAge(18). Also, even if you retrieve this value that's wrong you are not using it, so it is useless. You are also comparing an array (age) to an integer. This operation can't be done because the two objects cannot be compared, it's like comparing apple and pears Commented Jul 20, 2022 at 8:23

2 Answers 2

3

To filter the array you can do this:

var resultArray = age.Where(item => item >= 18).ToArray();

or use the FindAll:

var resultArray = Array.FindAll(age, item => item >= 18);

The first option uses an extension methods named Where that operates on IEnumerable, which arrays implement. IEnumerable is an interface for a sequence of elements that can be stepped through one after the other.

The second option uses FindAll, which is actually built in to the Array class.

For more info you can look at this post.

Sign up to request clarification or add additional context in comments.

4 Comments

You'll need using System.Linq; for this to work.
Your solution is surely correct, but I like more the one provided by @tymtam because it provides better performance and less memory usage (I find no difference in terms of readability)
@MatteoUmili Removing .ToArray would reduce memory usage
Yeah, .ToArray() is abundant here if the only thing OP needs to do is foreach and WriteLine.
2

You are so close!

foreach (int item in age)
{
    if (item>= targetAge)
    {
        Console.WriteLine(item);
    }
}

2 Comments

There are two changes here: 1. You have if outside of foreach and that's incorrect. 2. It's if (item >= , not if (age>=
@IndieDev if the code you wrote is the real one then age is an int[], so item must be an int. You also wrote that targetAge is an int so the code wrote by @tymtam is correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.