using System;
using System.Collections.Generic;
namespace exercise_69
{
class Program
{
public static void Main(string[] args)
{
List<int> numbers = new List<int>();
//creating a list called numbers
while (true)
{
int input = Convert.ToInt32(Console.ReadLine());
if (input == -1)
{
break;
}
numbers.Add(input);
}
//fills a list called numbers until user enters " -1 "
Console.WriteLine("from where");
int lownum = Convert.ToInt32(Console.ReadLine());
//lowest number to get printed
Console.WriteLine("where to");
int highnum = Convert.ToInt32(Console.ReadLine());
//highest number to get printed
foreach(int number in numbers)
{
if(lownum < number || highnum > number)
{
Console.WriteLine(numbers);
} //trying to filter the numbers and print them
}
}
}
}
Blockquote
the issue i am having is when i run the program the console just tells me this "System.Collections.Generic.List`1[System.Int32]" so my question is how do i properly filter or remove numbers from a list within a certain value ( not index )
CodePudding user response:
the console just tells me this "System.Collections.Generic.List`1[System.Int32]"
That's because you did this:
Console.WriteLine(numbers);
numbers
is a List<int>
, it's a whole collection of numbers not just a single number. Console.WriteLine
has many varaitions ("overloads") that know how to do all different kinds of things. It has a large quantity of specific variations for numbers, strings, etc and there is one variation that's like a "catch-all" - it accepts an object
which means it can accept pretty much anything in the C# universe. The only thing it does with it, if you do manage to end up using this variation (overload), is call ToString()
on whatever you passed in, and then print the string it gets back.
Because you passed a List<int>
in, and Console.WriteLine doesn't have any variation that does anything cool with a List specifically, it means your passed-in List gets treated by the catch-all version of WriteLine; "call ToString on what was passed in and print the result". Because List doesn't have a very specific or interesting ToString()
of its own, it just inherits a version of ToString()
from object
, the most simple root of all things in C#. Object's ToString() doesn't do very much - it just returns the type of the object which, in this case, is a "System.Collections.Generic.List`1[System.Int32]".. and that's why you see what you see in the console
Now that you know why your code is printing the type of the List, because you're passing in a List, can you see how to change it so you're passing in something else (like, e.g. an actual number you want to print) ?
Console.WriteLine(numbers);
^^^^^^^
this needs to be something else - can you work out what?