patterncsharpModerate
Select case string comparison
Viewed 0 times
caseselectstringcomparison
Problem
I have a select case that checks against a string variable. It's starting to get large and I am wondering if there is a better way of doing this?
Here is a sample of the
This actual list will be about 50 - 80 comparisons. Is this the fastest way to do this or is there a better way?
Here is a sample of the
Select Case statement:Select Case Param.ToLower
Case "dashboard_home_vm"
Return _Locator.DashboardHome_VM
Case "job_list_vm"
Return _Locator.JobList_VM
Case "job_add_vm"
Return _Locator.JobAdd_VM
Case "client_add_vm"
Return _Locator.ClientAdd_VM
Case "client_list_vm"
Return _Locator.ClientList_VM
Case "client_report_vm"
Return _Locator.ClientReport_VM
Case "employee_add_vm"
Return _Locator.EmployeeAdd_VM
Case "employee_certification_vm"
Return _Locator.EmployeeCertification_VM
Case "employee_list_vm"
Return _Locator.EmployeeList_VM
Case "employee_report_vm"
Return _Locator.EmployeeReport_VM
Case "employee_role_vm"
Return _Locator.EmployeeRole_VM
Case "employee_timeslip_vm"
Return _Locator.EmployeeTimeslip_VM
Case "product_add_vm"
Return _Locator.ProductAdd_VM
Case "product_category_vm"
Return _Locator.ProductCategory_VM
Case "product_list_vm"
Return _Locator.ProductList_VM
Case "product_type_vm"
Return _Locator.ProductType_VM
Case "product_unit_vm"
Return _Locator.ProductUnit_VM
Case "tracking_stock_vm"
Return _Locator.TrackingInStock_VM
Case "tracking_list_vm"
Return _Locator.TrackingList_VM
Case "tracking_site_vm"
Return _Locator.TrackingOnSite_VM
Case "vendor_add_vm"
Return _Locator.VendorAdd_VM
Case "vendor_list_vm"
Return _Locator.VendorList_VM
Case "vendor_report_vm"
Return _Locator.VendorReport_VM
Case Else
Return Nothing
End SelectThis actual list will be about 50 - 80 comparisons. Is this the fastest way to do this or is there a better way?
Solution
A classic solution to this problem is to use a data table - in your case probably in form of a dictionary. It depends of what type your values are - I assume they are some sort of view models? I'm also going to assume they have a common base class:
One time setup:
You can look them up simply by
Adding a new view model would be achieved by simply adding a new entry to the dictionary.
One time setup:
Dim dict As New Dictionary(Of String, ViewModelBase)
dict.Add("dashboard_home_vm", _Locator.DashboardHome_VM)
...You can look them up simply by
Dim vm As ViewModelBase
If (dict.TryGetValue(Param.ToLower, vm)) Then
return vm
End If
return NothingAdding a new view model would be achieved by simply adding a new entry to the dictionary.
Code Snippets
Dim dict As New Dictionary(Of String, ViewModelBase)
dict.Add("dashboard_home_vm", _Locator.DashboardHome_VM)
...Dim vm As ViewModelBase
If (dict.TryGetValue(Param.ToLower, vm)) Then
return vm
End If
return NothingContext
StackExchange Code Review Q#35877, answer score: 12
Revisions (0)
No revisions yet.