using System;
using System.Data;
namespace ConsoleMinMax
{
class MinMaxValue
{
static void Main(String[] args)
{
int[] tableWithValue = { 0, 0, 0, 0, 0 }; //This is a wrong way
int i = 0;
for (; i < 5; i )
{
Console.WriteLine("Get number");
int number = Convert.ToInt32(Console.ReadLine());
tableWithValue[i] = number;
}
Console.WriteLine("Min value: " tableWithValue.Min());
Console.WriteLine("Max value: " tableWithValue.Max());
}
}
}
I tried made a new table with user input to check max and min value. But I haven't idea how I can add user input value to table. I thought that value may add method tableWithValue.Append(number) like in Python but doesn't work in C#. Please for help.
CodePudding user response:
In order to use Linq, in your case .Min()
and .Max()
you should add using System.Linq
:
using System;
using System.Data;
using System.Linq; // <- you are going to query with a help of Linq (Min, Max etc.)
...
// It should compile now
Console.WriteLine($"Min value: {tableWithValue.Min()}");
Console.WriteLine($"Max value: {tableWithValue.Max()}");
...
To brush your code slightly:
using System;
using System.Data;
using System.Linq;
namespace ConsoleMinMax
{
class MinMaxValue
{
static void Main(String[] args)
{
// Array of 5 items
int[] tableWithValue = new int[5];
// do not use magic contsants - 5 - but tableWithValue.Length
for (int i = 0; i < tableWithValue.Length; i )
{
Console.WriteLine("Get number");
//TODO: Better int.TryParse to validate user input
int number = Convert.ToInt32(Console.ReadLine());
// why =? Just assign =
tableWithValue[i] = number;
}
// Time to simple Linq
Console.WriteLine($"Min value: {tableWithValue.Min()}");
Console.WriteLine($"Max value: {tableWithValue.Max()}");
}
}
}
CodePudding user response:
You are using array and array do not have "add" method (they can be concatenated with other array). For what you need to use list, like:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleMinMax
{
class MinMaxValue
{
static void Main(String[] args)
{
var tableWithValue = new List<int>();
for (var i = 0; i < 5; i )
{
Console.WriteLine("Get number");
int number = Convert.ToInt32(Console.ReadLine());
tableWithValue.Add(number);
}
Console.WriteLine("Min value: " tableWithValue.Min());
Console.WriteLine("Max value: " tableWithValue.Max());
}
}
}
CodePudding user response:
Gentlemen, please, use LINQ consistently and idiomatically:
var tableWithValue = Enumerable.Range(0, 5)
.Select(i =>
{
Console.Write("Get number: ");
return int.Parse(Console.ReadLine());
})
.ToList();
Console.WriteLine("Min value: " tableWithValue.Min());
Console.WriteLine("Max value: " tableWithValue.Max());