I am trying to define the contents of an array. A way of achieving what I want is shown below for a simplified example.
Is there a better way of doing it? This seems like a pretty messy way of achieving something that I feel should be easily done. Could I use lists? Or would a database work (I don't know anything about how to use databases but feel that this is the kind of thing they would be good at).
Thanks in advance
for (int i = 0; i < NumberOfBoxes; i++)
{
BoxName[0] = "Blue box";
if (i == 1) { break; }
BoxName[1] = "Red box";
if (i == 2) { break; }
BoxName[2] = "Yellow box";
if (i == 3) { break; }
BoxName[3] = "Green box";
if (i == 4) { break; }
BoxName[4] = "White box";
if (i == 5) { break; }
BoxName[5] = "Black box";
if (i == 6) { break; }
}
What I really want to do is to just use this code:
BoxName[0] = "Blue box";
BoxName[1] = "Red box";
BoxName[2] = "Yellow box";
BoxName[3] = "Green box";
BoxName[4] = "White box";
BoxName[5] = "Black box";
And if there are only 4 boxes then the compiler just magically knows to ignore BoxName[4] and BoxName[5] rather than throwing an error like it currently does.
You can create one array with all the options, and then just copy as many as you need:
// This declaration could be for a private static readonly variable, given that
// you won't change the contents
string[] allBoxes = { "Blue box", "Red box", "Yellow box", "Green box",
"White box", "Black box" };
Array.Copy(allBoxes, BoxName, NumberOfBoxes);
If you don't already have the array, you could potentially use a List<string>
, fill it completely, then use List<T>.RemoveRange
to trim it:
List<string> boxes = new List<string> { "Blue box", "Red box", "Yellow box",
"Green box", "White box", "Black box" };
boxes.RemoveRange(numberOfBoxes, boxes.Count - numberOfBoxes);
Or use LINQ:
List<string> boxes = new[] { "Blue box", "Red box", "Yellow box",
"Green box", "White box", "Black box" }
.Take(numberOfBoxes)
.ToList(); // Or ToArray if you really want an array
There are really lots of options.
It's not really clear what your situation is though - there may be better alternatives. With more context, we can help you better.
See more on this question at Stackoverflow