我想构建一个用于订购集合的委托:
switch(vm.OrderBy){
case "Title":
vm.Albums = _albumRepo.Get(a => a.Title);
break;
case "Artist":
vm.Albums = _albumRepo.Get(a => a.Artist.Name);
break;
case "Price":
vm.Albums = _albumRepo.Get(a => a.Price);
break;
我的存储库方法是:
public IEnumerable<Album> Get(Func<Album, string> orderingDelegate = null)
{
IEnumerable<Album> albums;
if (orderingDelegate == null)
albums = _context.Albums.OrderBy(a => a.Title);
else
albums = _context.Albums.OrderBy(orderingDelegate);
return albums;
}
所以,我将Func<Album, string>
传递给我的Get()方法,只要order属性是String类型,这个方法就很好。但是,价格是小数,因此不会编译:
_albumRepo.Get(a => a.Price);
我是否需要创建另一个Get方法,以便我可以按小数订购?
public IEnumerable<Album> Get(Func<Album, decimal> orderingDelegate = null){ }
或者有更好的方法吗?
谢谢!
克里斯
答案 0 :(得分:3)
您可以将签名更改为通用签名吗?
public IEnumerable<Album> Get<T>(Func<Album, T> orderingDelegate = null)
{
IEnumerable<Album> albums;
if (orderingDelegate == null)
albums = _context.Albums.OrderBy(a => a.Title);
else
albums = _context.Albums.OrderBy(orderingDelegate);
return albums;
}
答案 1 :(得分:1)
你可以做一个简单的解决方案:
public IEnumerable<Album> Get(Func<Album, object> orderingDelegate)
{
return _context.Albums.OrderBy(orderingDelegate);
}