我写了这种方法,但是我想对其进行优化。
我认为TResult output
(Into
中Pagination.cs
方法中的参数)以及new HomeProjectViewModel()
(ProjectService.cs
中的参数)都可以删除,但我不能! / p>
是否可以从方法中删除此参数?
Pagination.cs
public static class Pagination
{
public static async Task<TResult> Into<T, TSource, TResult>(this IQueryable<T> query, Func<List<T>, List<TSource>> source, TResult output, int page, int showLimit)
{
if (query == null) return output;
var que = page > 1
? await query.Skip(showLimit * (page - 1)).Take(showLimit).Cacheable().ToListAsync().ConfigureAwait(false)
: await query.Take(showLimit).Cacheable().ToListAsync().ConfigureAwait(false);
var list = source.Invoke(que);
var type = output.GetType();
var pages = type.GetProperty("Pages");
var currentPage = type.GetProperty("CurrentPage");
var items = type.GetProperty("Items");
if (pages == null || currentPage == null || items == null) return output;
pages.SetValue(output, Numbers.RoundToUp((double)(await query.CountAsync().ConfigureAwait(false)) / showLimit));
currentPage.SetValue(output, page);
items.SetValue(output, list);
return output;
}
ProjectService.cs
public async Task<HomeProjectViewModel> HomeProjects(int page, int showLimit = 5)
{
var query = from project in _project
let pictures = from picture in project.Pictures where !picture.Deleted select picture.Filename
where !project.Deleted && !project.Hidden
orderby project.Added descending
select new
{
project.SmartId,
project.Text,
pictures,
};
return await query.Into(que =>
que.Select(project => new HomeProjectItemViewModel
{
SmartId = project.SmartId,
Name = project.Text,
Image = project.pictures.SelectRandom()
}).ToList(), new HomeProjectViewModel(), page, showLimit);
}
HomeProjectViewModel.cs
public class HomeProjectViewModel
{
public List<HomeProjectItemViewModel> Items { get; set; }
public int CurrentPage { get; set; }
public int Pages { get; set; }
}
此方法将是创建包含页面,当前页面等的类的快捷方式。
在我的项目中,许多方法看起来像HomeProjects()
我想创建方法而不是多行代码。