I know I can create a generic method that I can call from other methods similar to the following, but it seems like a waste to have a seperate method when all I want to do is have a variable within a method be defined as generic:
private List<T> OrderedEntityList<T>(IRepository<T> repository) where T : Entity, IOrderedEntity
{
return repository.All().OrderBy(x => x.DisplayOrder).ToList();
}
public SomeMethod()
{
entityList = OrderedEntityList(_memberRepository);
foreach (var entityRecord in entityList)
{
//... do work ...
}
}
What I want is to do something like the following, where I can pass in the name of the repository as a parameter, but as it is, this doesn’t compile.
public SomeMethod(string repositoryName)
{
List<T> entityList where T : Entity, IOrderedEntity = repository<T>.All().OrderBy(x => x.DisplayOrder).ToList();
foreach (var entityRecord in entityList)
{
//... do work ...
}
}
Any thoughts on how do to this?
— EDIT —
Thanks all for the quick feedback. Looks like I need to provide some additional information. Basically I renamed my method to make it easier for an example, but in reality, what I am trying to do is have a generic action in an MVC controller that can be used to display a list of entities (that all inherit from Entity and IOrderedEntity) which might include members, statuses, roles, etc. I am trying to make my MVC controller actions reusable regardless of the type of underlying repository (as long as each implements the same interface). Here’s my actual List method in my controller that I am trying to make “generic”.
public ActionResult List(string entity)
{
//TODO: Find out how to declare this as a generic list instead of tying it to MemberStatus
List<MemberStatus> entityList;
EntityIndexViewModel<OrderedEntityViewModel> indexViewModel;
//TODO: Possibly move this switch statement to an EntityFactory (once I find out how...)
switch (entity)
{
case "Status":
indexViewModel = new EntityIndexViewModel<OrderedEntityViewModel>();
//TODO: This is another line that I think is a waste to have as seperate method... but maybe I'm wrong
entityList = OrderedEntityList(_memberStatusRepository);
ViewBag.EntityName = "Member Statuses";
break;
default:
throw new Exception("Entity is not valid");
}
foreach (var entityRecord in entityList)
{
var viewModel = new OrderedEntityViewModel();
viewModel.Id = entityRecord.Id;
viewModel.Name = entityRecord.Name;
viewModel.DisplayOrder = entityRecord.DisplayOrder;
viewModel.HasChildRecordsAssigned = _memberRepository.All().Any(m => m.StatusId == entityRecord.Id);
indexViewModel.EntityList.Add(viewModel);
}
return View("List", indexViewModel);
}
You could do something like this:
But depending on the rest of your code, maybe what you really want is to take advantage of generic type variance in C# 4.0.