-3

enter image description here

I did this already by turning the list into an arrays, but how do i do this without an array

riffnl
  • 3,248
  • 1
  • 19
  • 32
Medicute
  • 1
  • 2
  • 1
    Please paste code as text, not as image. – PMF May 31 '22 at 12:59
  • 4
    [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551) – 001 May 31 '22 at 12:59
  • Why not just use `foreach` on `nummern`? – Maxim May 31 '22 at 13:01
  • You are already using an array hidden inside `List<>`. So what is the point of saying not to use an array? Did you mean to say not to use a loop or something like that? – John Alexiou May 31 '22 at 13:08
  • The number of elements in a List is given by the Count property - so instead of creating an array use the list in the for loop checking for "i < nummern.Count;". – PaulF May 31 '22 at 13:14

4 Answers4

1

You could use foreach:

foreach (int num in nummern) {
  if (num % 3 == 0)
    // your code goes here
}

or with an lambda to get rid of the if:

foreach (int num in nummern.FindAll(n => n % 3 == 0)) {
  // your code goes here
}

or directly create a new List:

List<int> nummernMod3 = nummern.FindAll( n => n % 3 == 0 );

Note that you could also use Where instead of FindAll. There is a separate SO question that may help you decide.

izlin
  • 2,129
  • 24
  • 30
0

You could easily use

var ziffern = nummern.Where(n => n%3 == 0);

Then you could iterate on it (it's an Enumerable) or convert it to array or to list (.ToArray() or .ToList()) or whatever you need...

Marco
  • 56,740
  • 14
  • 129
  • 152
0

You can use foreach

foreach (int x in nummern)
            {
                if (x % 3 ==0)
                {
                    Console.WriteLine(x);
                }
            }
0

It's already a list, so there is no actual need to convert it to an Array

    var list = new List<int>(){1,2,3,4,5,6};
    
    // Method 1 - for loop
    for(var i = 0; i < list.Count(); i++)
    {
        if (list[i] % 3 == 0) Console.WriteLine(list[i]);
    }
    
    // Method 2 - foreach loop
    foreach(var num in list)
    {
        if (num % 3 == 0) Console.WriteLine(num);
    }
    
    // Method 3 - using LinQ
    var results = list.Where(x => x % 3 == 0); // this will result in a new list of results
    Console.WriteLine(string.Join(",", results));
riffnl
  • 3,248
  • 1
  • 19
  • 32