so I am trying to take all the numbers from a list that are less than 5 and I try to put them in another list and print that list. I have no idea how to do that in c#. I will be very grateful if you'd help me. Thank you and here is my code:
using System;
namespace exercices
{
class Hello
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3, 4, 5, 6, };
int[] b = { };
for (int i = 0; i < a.Length; i )
{
if (a[i] < 5)
{
b.Append(a[i]);
}
}
}
}
CodePudding user response:
Method 1. Just check every element
You should use List<T>
collection in this method. It's possible to convert it to array later, if you need.
List<int> b = new();
foreach (int element in a)
{
if (element < 5)
{
b.Add(element);
}
}
Method 2. Use Array.FindAll<T>
method
int[] b = Array.FindAll(a, element => element < 5);
Method 3. Use LINQ
int[] b = a.Where(element => element < 5).ToArray();
CodePudding user response:
You could do something like this:
for (int i = 0; i < a.Length; i )
{
Int number=a[i];
if (number < 5)
b.Insert(i, number);
}