0

I have Checkboxes within my application and if one is checked, a value has to be added to a List / Array

Question: Is there a way to write this code more simple / smart?

My Approach:

List<string> animals = new List<string>();
if (CheckBox_dog.Checked == true)
    animals.Add("dog");
if (CheckBox_cat.Checked == true)
    animals.Add("cat");
if (CheckBox_horse.Checked == true)
    animals.Add("horse");
if (CheckBox_duck.Checked == true)
    animals.Add("duck");
if (CheckBox_chicken.Checked == true)
    animals.Add("chicken");
if (CheckBox_cow.Checked == true)
    animals.Add("cow");
if (CheckBox_pig.Checked == true)
    animals.Add("pig");
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Toshi
  • 2,532
  • 4
  • 17
  • 45
  • 5
    I believe this question rather belongs on [CodeReview](https://codereview.stackexchange.com/). Nevertheless, what you could do is create a function that adds an element to the list if a condition is true, which you could declare like `ConditionalListAdd(bool condition, string value)`. Also note that you can omit the `== true` from the `if` statements, as there is no point in comparing a boolean to a boolean. – Ian H. Nov 20 '17 at 07:26
  • 2
    For starters, `if (CheckBox_dog.Checked == true)` is just a longer way of writing `if (CheckBox_dog.Checked)`. – oerkelens Nov 20 '17 at 07:28

2 Answers2

2

Given that your CheckBoxes are placed in your form (change accordingly if they are placed inside another container). Use LINQ:

List<string> animals = Controls.OfType<CheckBox>().Where(c => c.Checked)
                               .Select(c => c.Name.Split('_')[1]).ToList();

However you can use a Dictionary as an another approach. Something like this https://stackoverflow.com/a/42505360/2946329

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
0
// chklData is a CheckboxList control
List<string> dataList = new List<string>(chklData.Items.Count);
foreach (ListItem item in chklData.Items)
{
    if (item.Selected) { dataList.Add(item.Value); }
}

OR

// divCheckBoxes is a container like div or panel
List<string> pageItemsList = new List<string>(30); // Developer approximate number
foreach (var ctrl in divCheckBoxes.Controls)
{
    CheckBox chk = ctrl as CheckBox;
    if(chk == null) { continue; }
    if(chk.Attributes["CustomAttribute"] != "CustomValue") { continue; }
    if (chk.Checked) { dataList.Add(chk.Attributes["CustomValueAttribute"]); }
}
Hope Mystery
  • 338
  • 2
  • 5