1

I need help with this loop and displaying the array correctly into a label. Here is the Code

private void ErrorEquipment()
{
    string[] Equips = { "Projector", "Computer", "Network", "Webcam" };

    for (int i = 0; i <= 3; i++)
    {
        if (venue.Equipment[i] == true)
        {
            lblEquipment.Text = ("Room Has " + Equips[i]);
        }
    }
}

What I want is to check if the venue has the equipment and if so it, display what equipment the venue has in a label. Currently it checks that but if a venue has more than one equipment available and it overwrites the first equipment that was put in the label.

1
  • Do you want to concat all equipments in the same label? Commented Jan 25, 2015 at 14:55

3 Answers 3

2

That's because you redefine your variable lblEquipment.Text in every iteration. Try this instead:

    lblEquipment.Text = "Room Has ";
    for (int i = 0; i <= 3; i++)
    {
        if (venue.Equipment[i] == true)
        {
            lblEquipment.Text += Equips[i] + " ";
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it something like this.

lblEquipment.Text = "Room Has ";
for (int counter = 0; counter <= 3; counter++)
{
    if (venue.Equipment[counter] == true)
        lblEquipment.Text += Equips[counter] + " ";
}

But this is too inefficient because when you concatenate strings, it always creates a new instance of string because string is immutable, and since you're in a for loop, the instance you're creating is being wasted.

To better implement this, you must create a StringBuilder object and then ToString it after the loop. Something like this.

StringBuilder builder = new StringBuilder();
builder.Append("Room Has ");
for (int counter = 0; counter <= 3; counter++)
{
    if (venue.Equipment[counter] == true)
        builder.Append(Equips[counter] + " ");
}
lblEquipment.Text = builder.ToString();

More info about Immutable objects here: C# Tips & Tricks: Immutable Types

Comments

1

you are replacing each time Label lblEquipment value.

you need to do String Concatenation instead of just assigning new value.

Use a variable to Store result and then display:

 string rooms ="Room Has ";
 for (int i = 0; i <= 3; i++) 
{ 
  if (venue.Equipment[i] == true) 
     rooms += ","+Equips[i]; // concatenating with previous value
}
lblEquipment.Text = rooms;

A linq inspired solution would be:

var result = venue.Equipment.Select((v, index) => new { v, index })
                            .Where(pair => pair.v == true && pair.index <=3)
                            .Select(pair => Equips[pair.index]);

lblEquipment.Text = "Room Has "+ string.Join(",",result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.