1

我想建立一个用于订购集合的委托:

 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;
    }

因此,我将 a 传递Func<Album, string>给我的 Get() 方法,只要 ordering 属性是 String 类型,它就很好。但是,价格是小数,因此无法编译:

_albumRepo.Get(a => a.Price);

我是否需要创建另一个 Get 方法才能使用小数排序?

public IEnumerable<Album> Get(Func<Album, decimal> orderingDelegate = null){ }

还是有更好的方法来做到这一点?

谢谢!

克里斯

4

2 回答 2

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;
}
于 2013-07-24T12:23:50.457 回答
1

你可以做一个简单的解决方案:

public IEnumerable<Album> Get(Func<Album, object> orderingDelegate)
{
    return _context.Albums.OrderBy(orderingDelegate);
}
于 2013-07-24T12:15:42.147 回答