C# 使用各种数据类型排序委托
我想构建一个用于订购集合的委托:C# 使用各种数据类型排序委托,c#,.net,linq,C#,.net,Linq,我想构建一个用于订购集合的委托: switch(vm.OrderBy){ case "Title": vm.Albums = _albumRepo.Get(a => a.Title); break; case "Artist": vm.Albums = _albumRepo.Get(a => a.Artist.Name);
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;
}
我是否需要创建另一个Get方法,以便可以用小数排序
public IEnumerable<Album> Get(Func<Album, decimal> orderingDelegate = null){ }
public IEnumerable Get(Func orderingDelegate=null){}
还是有更好的方法
谢谢
Chris您可以执行以下简单的解决方案:
public IEnumerable<Album> Get(Func<Album, object> orderingDelegate)
{
return _context.Albums.OrderBy(orderingDelegate);
}
public IEnumerable Get(Func orderingDelegate)
{
return _context.Albums.OrderBy(orderingDelegate);
}
您可以执行以下简单的解决方案:
public IEnumerable<Album> Get(Func<Album, object> orderingDelegate)
{
return _context.Albums.OrderBy(orderingDelegate);
}
public IEnumerable Get(Func orderingDelegate)
{
return _context.Albums.OrderBy(orderingDelegate);
}
您可以将签名更改为通用签名吗
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;
}
公共IEnumerable Get(Func orderingDelegate=null)
{
数不清的相册;
如果(orderingDelegate==null)
albums=\u context.albums.OrderBy(a=>a.Title);
其他的
albums=\u context.albums.OrderBy(orderingDelegate);
归还相册;
}
您可以将签名更改为通用签名吗
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;
}
公共IEnumerable Get(Func orderingDelegate=null)
{
数不清的相册;
如果(orderingDelegate==null)
albums=\u context.albums.OrderBy(a=>a.Title);
其他的
albums=\u context.albums.OrderBy(orderingDelegate);
归还相册;
}
太棒了!我不知道这是怎么回事,但我接受了!Thx。我非常确定,由于装箱操作正在进行,许多LINQ提供商都无法使用此功能。我假设它与值类型的属性(如
int
)一起使用时会引发运行时异常。太棒了!我不知道这是怎么回事,但我接受了!Thx。我非常确定,由于装箱操作正在进行,许多LINQ提供商都无法使用此功能。我假设它与值类型的属性(如int
)一起使用时会引发运行时异常。当我必须在没有委托的情况下调用Get()时,这有点尴尬-Get()-但这肯定是一个比我现有的更好的解决方案。我可以。当我必须在没有委托的情况下调用Get()时,这有点尴尬-Get()-但这肯定是一个比我现有的更好的解决方案。