Home > OS >  C# Select a list relying on what user inputs
C# Select a list relying on what user inputs

Time:10-13

I got a problem that is driving me crazy. I state I want to avoid the if statements to make the code smarter and cleaner. I have a combobox with 7 items and if the user choose the first item the program does something working with a specific list with the same name contained in a class, if he choose the second the program does another thing with another list contained in the same class.

The code is this:

        if (cbb1.SelectedItemPosition == 0)
        {
            lblResult.Text = DoSomething(ClassList.List1);
        }

        else if (cbb1.SelectedItemPosition == 1)
        {                
            lblResult.Text = DoSomething(ClassList.List2);
        }

Now I'm going to add another combobox and combining all the possible if statements will be difficult and cumbersome IMHO. So I'm thinking to use tuples to associate the combobox SelectedItemPosition to the list name to let the code simply be something like this:

lblResult.Text = DoSomething(ComboboxItemConvertedToItsCorrespondingList);

Maybe is easier than I think, but I can't do that.

Sorry for my English and thanks guys.

EDIT: Dictionary works wonderfully. I removed about 30 lines of code! Thank you all guys

CodePudding user response:

Create a Dictionary<int, List<object> and add the mapping to it accordingly with key as the index of combobox item. And pass only the selected index to the method and perform the logic on dictionary value which is ultimately the list.

CodePudding user response:

To directly answer your question with your methodology, you should easily be able to take care of this with a List:

Where List1 is the type of ClassList.List1:

List<List1> sublist = new List<List1>() {
    ClassList.List1,
    ClassList.List2,
};
// Other code
lblResult.Text = DoSomething(subList[cbb1.SelectedItemPosition]);
  •  Tags:  
  • c#
  • Related