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);
}
}
CodePudding user response:
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.
CodePudding user response:
You are so close!
foreach (int item in age)
{
if (item>= targetAge)
{
Console.WriteLine(item);
}
}