I have the following two methods that get data from my DB and return a populated SelectList object (including an “All” option value) that I then pass onto my view. The problem is that they are almost identical with the exception that they both access different repository objects and they have different ID names (StatusId and TeamId). I think there is an opportunity to refactor them into a single method that accepts the repository as a parameter and somehow figures out what the ID name should be, perhaps by using reflection or some sort of lambda expression, but I don’t know quite how to accomplish this.
private SelectList GetStatusSelectList(int selectedStatusId)
{
List<MemberStatus> statusList = _memberStatusRepository.All().ToList();
statusList.Insert(0, new MemberStatus {StatusId = 0, Name = "All"});
var statusSelectList = new SelectList(statusList, "StatusId", "Name", selectedStatusId);
return statusSelectList;
}
private SelectList GetTeamSelectList(int selectedTeamId)
{
List<MemberTeam> teamList = _memberTeamRepository.All().ToList();
teamList.Insert(0, new MemberTeam { TeamId = 0, Name = "All" });
var teamSelectList = new SelectList(teamList, "TeamId", "Name", selectedTeamId);
return teamSelectList;
}
Can anyone help figure out how to refactor these into a single method?
you may try the following:
This solution is not ideal and relies on some conventions (e.g. all your items should have
Nameproperty). However it seems to be a not bad way to start with. It may be improved further by using Expressions instead of property names — that would allow to change property names with compile time check.