Home > Back-end >  How to limit an array value between a certain range
How to limit an array value between a certain range

Time:11-19

I want the values in the array to be between 1 & 100 because they’re grades for a test. How do I do this? Is it possible?

I’ve used a for loop to take in the contents of the array

CodePudding user response:

Its quite easy to filter the array after the fact with LINQ. Then use only the validated grades

int[] rawGrades = {100, 87, 999};
int[] validGrades = rawGrades
    .Where(g => g <= 100 && g >=0)
    .ToArray(); // {100, 87}

Validating this upfront would be possible, but would lead to some potentially weird but valid nonetheless code. Off the top of my head I can imagine you make a Grade class, which will contain a Score property, wherein you can have your setter intervene

public class Grade
{
    private int _score;
    public int Score
    {
        get => _score;
        set => _score = value >= 0 && value <= 100 ? value : throw new ArgumentException("Grades must be from 0-100 inclusive");
    }
}

Grade[] grades = new Grade[];
grades[0] = new Grade { Score = 99 }; //valid
grades[1] = new Grade { Score = 99999 }; //invalid, will throw exception

//get the grades as int's with some LINQ also
int[] scores = grades.Select(g => g.Score).ToArray()

There is always the option of validating the input grade prior to it being added to the array, which is the simplest option

CodePudding user response:

To solve the problem, reframe it. What you need is something that represents a number from 1 to 100. Once you have that, you can put more than one in an array, list, etc.

The tendency is to use existing numeric types like int, single, decimal, etc. That can work, but as you've recognized there's always a risk that some code (or some person) will accidentally set a value that's out of range.

There's are different ways to create what you need. Here's just one:

public class TestScore
{
    public byte Score { get; }

    public TestScore(byte score)
    {
        if (score < 1 || score > 100)
        {
            throw new ArgumentOutOfRangeException(
                $"{nameof(score)} must be in the range of 1 to 100.");
        }
        Score = score;
    }
}

TestScore is a class that contains a value Score and restricts what that value can be. You can't create an instance of TestScore without providing a valid value. Once the score is set, it can't be changed. That means if you have an instance of TestScore, it's guaranteed to have a valid score between 1 and 100.

Now you can put them in an array.

var testScores = new TestScore[5];

...or a list, or any other collection.

var testScores = new List<TestScore>();

I used byte because it uses less memory than int (only values from 0 to 255) but it's splitting hairs. It probably doesn't matter. If you wanted to have scores with decimal places (75.5) you could use single.

Or you might decide that the score should be represented as a number between 0 and 1, like 0.0, .75, or 1. In that case you could use a single and validate that it's >= 0 and <=1.

CodePudding user response:

If you want to declare an array, which contains exactly 100 elements, do that using a constructor just like below:

int[] array = new int[100];

If you don't know, how many elements will array have, use a List from System.Collections.Generics instead an array.

List<int> list = new List<int>();

CodePudding user response:

Values should be controlled before being inserted in the array

  •  Tags:  
  • c#
  • Related