private void ProductSearchManagerResultsRecieved(ProductSearchResult result) { if (result.HasError) { ErrorMessage = SearchResultRetrievalError; } else if (result.Product == null) { ErrorMessage = NoResults; } else { try { ErrorMessage = string.Empty; ProductPrice = decimal.Parse(result.Product.SalePrice); ProductImage = SetProductImage(result.Product.imageUrl); } catch { ErrorMessage = SearchResultDisplayError; } } IsSearching = false; RefreshUi(); }
public void When_a_search_is_cancelled_it_calls_back_with_a_cancelled_result() { ProductSearchResult results = null; // Arrange var mockRepo = MockRepository.GenerateMock <IProductSearchRepository <Product> >(); var searchResult = new Product(string.Empty, string.Empty); mockRepo.Stub(x => x.Search("product")).Do((Func <string, Product>) delegate { Thread.Sleep(2000); return(searchResult); }); // Act var searchWorker = new ProductSearchWorker(mockRepo, (cb, worker) => { results = cb; }, "product"); searchWorker.CancelSearch(); Thread.Sleep(5000); // Assert Assert.IsTrue(results.IsCancelled); }
/// <summary> /// 搜索结果 /// </summary> /// <param name="isSearchResultPage">是搜索结果页还是三级类别页(1为搜索结果页)</param> /// <returns></returns> public static ProductSearchResult GetProductSearchResult(SolrProductQueryVM vm) { //获取Condition ProductSearchCondition condition = GetSearchCondition(vm); if (vm.IsSearchResultPage == 1 && string.IsNullOrEmpty(condition.KeyWord) && condition.NValueList == null && condition.NValueList.Count <= 0) { return(new ProductSearchResult() { Navigation = new NavigationContainer(), ProductDataList = new Utility.PagedResult <Entity.SearchEngine.ProductSearchResultItem>() }); } if (!string.IsNullOrWhiteSpace(vm.MidCategoryID) && Convert.ToInt32(vm.MidCategoryID) > 0) { condition.Filters.Add(new FieldFilter("p_categorysysno2", vm.MidCategoryID)); } if (!string.IsNullOrWhiteSpace(vm.BrandID) && Convert.ToInt32(vm.BrandID) > 0) { condition.Filters.Add(new FieldFilter("p_brandid", vm.BrandID)); } //获取当前页面Querystring queryStringCollection = HttpContext.Current.Request.QueryString; //获取搜索结果 ProductSearchResult result = ProductSearchFacade.GetProductSearchResultBySolr(condition); return(result); }
public async Task <ProductSearchResult> GetModelListAsync(string keyword, DateTime?startTime, DateTime?endTime, int pageIndex, int pageSize) { using (MyDbContext dbc = new MyDbContext()) { ProductSearchResult result = new ProductSearchResult(); var entities = dbc.GetAll <ProductEntity>().AsNoTracking(); if (!string.IsNullOrEmpty(keyword)) { entities = entities.Where(a => a.Name.Contains(keyword)); } if (startTime != null) { entities = entities.Where(a => a.CreateTime >= startTime); } if (endTime != null) { entities = entities.Where(a => a.CreateTime.Year <= endTime.Value.Year && a.CreateTime.Month <= endTime.Value.Month && a.CreateTime.Day <= endTime.Value.Day); } result.PageCount = (int)Math.Ceiling((await entities.LongCountAsync()) * 1.0f / pageSize); var res = await entities.OrderByDescending(a => a.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); result.List = res.Select(a => ToDTO(a)).ToArray(); return(result); } }
public void When_a_search_is_performed_it_queries_the_repo_and_returns_results_asyncronously() { var isComplete = false; ProductSearchResult results = null; // Arrange var mockRepo = MockRepository.GenerateMock <IProductSearchRepository <Product> >(); var product = new Product(string.Empty, string.Empty); mockRepo.Stub(x => x.Search("product")).Return(product); // Act new ProductSearchWorker(mockRepo, (cb, worker) => { Thread.Sleep(500); isComplete = true; results = cb; }, "product"); // Confirm no return yet Assert.IsNull(results); while (!isComplete) { Thread.Sleep(1000); } // Assert mockRepo.AssertWasCalled(x => x.Search("product")); Assert.AreSame(product, results.Product); Assert.IsFalse(results.IsCancelled); }
private static void ExtractAggregations(ProductSearchResult result, IReadOnlyDictionary <string, IAggregate> aggregates) { result.StringAggregations = new Dictionary <string, Dictionary <string, long> >(); result.NumericAggregations = new Dictionary <string, NumericAggregation>(); foreach (var y in aggregates) { if (y.Value.GetType() == typeof(Nest.BucketAggregate)) { ExtractStringAggregation(result, y); } else if (y.Value.GetType() == typeof(Nest.ValueAggregate)) { var aggName = y.Key.Split('.')[0]; if (!result.NumericAggregations.ContainsKey(aggName)) { result.NumericAggregations.Add(aggName, new NumericAggregation()); } var agg = result.NumericAggregations[aggName]; switch (y.Key.Split('.')[1]) { case "min": agg.Min = ((ValueAggregate)y.Value).Value; break; case "max": agg.Max = ((ValueAggregate)y.Value).Value; break; case "avg": agg.Avg = ((ValueAggregate)y.Value).Value; break; } } } }
public SearchResponse(ProductSearchResult searchResult, SearchRequest request, HrefLookup hrefLookup, ICore core) : this() { _core = core; if (searchResult.Count > 0) { Filters = new ExtendedFilter(searchResult.Refinements, searchResult.SelectedRefinements, hrefLookup); Sorter = new ExtendedSorter(searchResult.SortingOptions, searchResult.SelectedSortingOption); var catName = hrefLookup.Forward.Get(ParsingHelper.GetHrefWithoutQueryString(request.Href)); var plpInfo = GetAdditionalPlpInfo(request, catName); foreach (var product in searchResult.Hits.Where(a => a.Price != Convert.ToDecimal(Config.Params.PriceToExclude)).ToList()) { Products.Add(new ProductListItem(product, GetExtraPLPInfo(plpInfo, product.ProductId), GetColorVariations(plpInfo, product.ProductId))); } Pager.PageSize = request.PageSize; Pager.CurrentPage = request.Page; Pager.RecordCount = searchResult.Count; Pager.TotalRecords = searchResult.Total; Pager.TotalPages = (int)Math.Ceiling((double)Pager.TotalRecords / Pager.PageSize); ProductIds = string.Join(",", Products.Select(x => x.ProductId)); Breadcrumbs = string.Join(" | ", Filters.Path.Select(x => x.Key.ToLowerInvariant())); } else { Breadcrumbs = "We're sorry, no products were found for your search"; } Term = searchResult.Query; Href = request.Href; }
private SearchPaginationViewModel BuildPaginationForSearchResults( ProductSearchResult searchResult, TParam searchParam, int maxPages) { var totalCount = searchResult.TotalCount; var itemsPerPage = SearchConfiguration.MaxItemsPerPage; var totalPages = (int)Math.Ceiling((double)totalCount / itemsPerPage); var param = new CreateSearchPaginationParam <TParam> { SearchParameters = searchParam, CurrentPageIndex = searchParam.Criteria.Page, MaximumPages = SearchConfiguration.ShowAllPages ? totalPages : maxPages, TotalNumberOfPages = totalPages, CorrectedSearchTerms = searchResult.CorrectedSearchTerms }; var pages = GetPages(param); var pager = new SearchPaginationViewModel { PreviousPage = GetPreviousPage(param), NextPage = GetNextPage(param), CurrentPage = pages.FirstOrDefault(p => p.IsCurrentPage), Pages = pages, TotalNumberOfPages = totalPages }; return(pager); }
private void SearchWorkerDoWork(object sender, DoWorkEventArgs e) { ProductSearchResult result = null; try { var productName = (string)e.Argument; using (var harness = new ProductRepositoryHarness(_repo)) { result = harness.Search(productName); } } catch (Exception ex) { Log.Error("SearchWorkerDoWork - Error.", ex); result = new ProductSearchResult(false, true, null); } finally { if (((BackgroundWorker)sender).CancellationPending) { e.Cancel = true; } e.Result = result; } }
public void When_a_search_is_performed_and_the_repository_fails_results_indicate_an_error_occurred() { var isComplete = false; ProductSearchResult results = null; // Arrange var mockRepo = MockRepository.GenerateMock <IProductSearchRepository <Product> >(); mockRepo.Stub(x => x.Search("product")).Do((Func <string, Product>) delegate { throw new Exception(); }); // Act new ProductSearchWorker(mockRepo, (cb, worker) => { isComplete = true; results = cb; }, "product"); while (!isComplete) { Thread.Sleep(1000); } // Assert mockRepo.AssertWasCalled(x => x.Search("product")); Assert.IsTrue(results.HasError); }
private static long GetFacetValue(ProductSearchResult results, string fieldName, string facetKey) { var aggregation = results.Aggregations?.SingleOrDefault(a => a.Field.EqualsInvariant(fieldName)); var item = aggregation?.Items.SingleOrDefault(x => x.Value.ToString() == facetKey); return(item?.Count ?? 0); }
// GET: RelatedProductsBlock public override ActionResult Index(ProductSearchBlock currentContent) { // We need to know which language the page we're hosted on is string language = ControllerContext.RequestContext.GetLanguage(); List <ProductListViewModel> productListViewModels; try { productListViewModels = currentContent.GetSearchResults(language); } catch (ServiceException) { return(View("FindError")); } if (productListViewModels == null) { // No hits, but we could still have manually added products productListViewModels = new List <ProductListViewModel>(); } // Override result with priority products MergePriorityProducts(currentContent, productListViewModels); // Editor could let this one be empty int resultsPerPage = currentContent.ResultsPerPage; if (resultsPerPage == 0) { resultsPerPage = 1000; // Default Find limit } if (productListViewModels.Count > resultsPerPage) { productListViewModels = productListViewModels.Take(resultsPerPage).ToList(); } if (productListViewModels.Any() == false) { return(View("EmptyResult")); } ProductSearchResult productSearchResult = new ProductSearchResult { Heading = currentContent.Heading, Products = productListViewModels }; // Track impressions TrackProductImpressions(productSearchResult); return(View(productSearchResult)); }
public static ProductSearchResult BuildProductSearchResult(ISearchResponse <Product> searchResponse) { var result = new ProductSearchResult() { TotalItems = searchResponse.Total, Products = searchResponse.Documents.ToList(), }; ExtractAggregations(result, searchResponse.Aggregations); return(result); }
private void ProcessSearchResult(ProductSearchResult result, IProductSearchWorker worker) { if (!result.IsCancelled) { if (ResultsRecieved != null) { ResultsRecieved(result); } } worker.Dispose(); }
public async Task <ProductSearchResult> GetProductsOnSale(int itemsPerPage, int itemsToSkip) { var query = _dbset.Where(x => x.SalePercentage != 0).Include(x => x.Images).Include(x => x.Subcategory).Include(x => x.Subcategory.Category); var productResult = new ProductSearchResult { TotalCount = await query.CountAsync(), Products = await query.OrderByDescending(x => x.DatePosted).Skip(itemsToSkip).Take(itemsPerPage).ToListAsync() }; return(productResult); }
public async Task <ProductSearchResult> GetProductsByBrand(string brand, int itemsPerPage, int itemsToSkip) { var query = _dbset.Include(x => x.Brand).Include(x => x.Images).Include(x => x.Subcategory).Include(x => x.Subcategory.Category).Where(x => x.Brand != null && string.Equals(x.Brand.Name, brand)); var productResult = new ProductSearchResult { TotalCount = await query.CountAsync(), Products = await query.OrderByDescending(x => x.DatePosted).Skip(itemsToSkip).Take(itemsPerPage).ToListAsync() }; return(productResult); }
// // GET: /Web/Product/ /// <summary> /// 搜索结果 /// </summary> /// <returns></returns> public ActionResult SearchResult() { //获取Condition ProductSearchCondition condition = GetSearchCondition(); //获取当前页面Querystring queryStringCollection = Request.QueryString; //获取搜索结果 ProductSearchResult result = ProductSearchFacade.GetProductSearchResultBySolr(condition, queryStringCollection); return(RedirectToAction("SearchResult", "Product")); }
public async Task <ProductSearchResult> GetProductsBySearch(SearchModel searchModel) { IQueryable <Product> query = null; if (!string.IsNullOrEmpty(searchModel.SearchName)) { query = _dbset.Where(x => x.ProductName.ToLower().Contains(searchModel.SearchName.ToLower()) || x.Description.ToLower().Contains(searchModel.SearchName.ToLower())) .Include(x => x.Images); } else { query = _dbset.Where(x => x.SubcategoryId == searchModel.SubcategoryId) .Include(x => x.Images); } if (searchModel.MinPrice.HasValue && searchModel.MaxPrice.HasValue) { query = query.Where(x => x.Price >= searchModel.MinPrice.Value && x.Price <= searchModel.MaxPrice.Value); } if (searchModel.ColorIds != null && searchModel.ColorIds.Count > 0) { query = query.Where(x => searchModel.ColorIds.Intersect(x.AvailableColors.Select(y => y.Id)).Count() > 0); } if (searchModel.Sizes != null && searchModel.Sizes.Count > 0) { var sizeQuery = query.Select(x => new { x.Id, x.Size }).ToList(); var productIds = new List <int>(); foreach (var product in sizeQuery) { if (product.Size != null && searchModel.Sizes.Intersect(product.Size.Replace(" ", string.Empty).Split(',').ToList()).Count() > 0) { productIds.Add(product.Id); } } query = query.Where(x => productIds.Contains(x.Id)); } query = query.Include(x => x.Subcategory).Include(x => x.Subcategory.Category).OrderByDescending(x => x.DatePosted); var productSearchResult = new ProductSearchResult { TotalCount = await query.CountAsync(), Products = await query.Skip(searchModel.ItemsToSkip).Take(searchModel.ItemsPerPage).ToListAsync() }; return(productSearchResult); }
private void TrackProductImpressions(ProductSearchResult productSearchResult) { foreach (var product in productSearchResult.Products) { GoogleAnalyticsTracking tracker = new GoogleAnalyticsTracking(ControllerContext.HttpContext); tracker.ProductImpression( product.Code, product.DisplayName, null, product.BrandName, null, "Product Search Block"); } }
public async Task <ProductSearchResult> GetTheNewestProducts(int itemsPerPage, int itemsToSkip, int daysToKeepProductNew) { var comparisonDate = DateTime.Now.AddDays((-1) * daysToKeepProductNew); var query = _dbset.Include(x => x.Images).Include(x => x.Subcategory).Include(x => x.Subcategory.Category); var productResult = new ProductSearchResult { TotalCount = await query.CountAsync(), Products = await query.OrderByDescending(x => x.DatePosted).Skip(itemsToSkip).Take(itemsPerPage).ToListAsync() }; return(productResult); }
private void SetUpSearchRepository() { var results = new ProductSearchResult { Facets = new List <Facet>(), Documents = new List <ProductDocument>() }; var mock = new Mock <ISearchRepository>(); mock.Setup(repository => repository.SearchProductAsync(It.IsAny <SearchCriteria>())).ReturnsAsync(results); _container.Use(mock); }
public IList <DemandWareProduct> GetProducts(String categoryId, int count) { String jsonResponse = JsonGetRequest(this.dwBaseUrl + "/product_search/images" + clientIdRequestParam + "&refine_1=cgid%3D" + categoryId + "&count=" + count); ProductSearchResult result = JsonConvert.DeserializeObject <ProductSearchResult>(jsonResponse); var products = result.hits; foreach (var product in products) { product.category_id = categoryId; } return(products); }
public override GetAutocompleteResult Execute(IUnitOfWork unitOfWork, GetAutocompleteParameter parameter, GetAutocompleteResult result) { if (!this.autocompleteSettings.ProductEnabled || !parameter.ProductEnabled || parameter.Query.IsBlank()) { return(this.NextHandler.Execute(unitOfWork, parameter, result)); } GetProductSettingsResult settings = this.productService.GetSettings(new GetSettingsParameter()); if (settings.ResultCode != ResultCode.Success) { return(this.CreateErrorServiceResult <GetAutocompleteResult>(result, settings.SubCode, settings.Message)); } if (!settings.CanSeeProducts) { return(this.CreateErrorServiceResult <GetAutocompleteResult>(result, SubCode.Forbidden, MessageProvider.Current.Forbidden)); } int maximumNumber = Math.Max(Math.Min(this.autocompleteSettings.ProductLimit, this.MaximumAutocompleteResults), this.MinimumAutocompleteResults); ProductSearchResult autocompleteSearchResults = this.productSearchProvider.GetAutocompleteSearchResults(parameter.Query, maximumNumber); result.Products = autocompleteSearchResults.Products.Select <ProductSearchResultDto, GetProductAutocompleteItemResult>((Func <ProductSearchResultDto, GetProductAutocompleteItemResult>)(o => { GetProductAutocompleteItemResult autocompleteItemResult = new GetProductAutocompleteItemResult(); autocompleteItemResult.Id = new Guid?(o.Id); autocompleteItemResult.Image = o.MediumImagePath ?? this.catalogGeneralSettings.NotFoundMediumImagePath; autocompleteItemResult.IsNameCustomerOverride = o.IsNameCustomerOverride; autocompleteItemResult.ManufacturerItemNumber = o.ManufacturerItemNumber; autocompleteItemResult.Name = o.Name; autocompleteItemResult.ErpNumber = o.ERPNumber; autocompleteItemResult.Title = o.ShortDescription; ICatalogPathBuilder catalogPathBuilder = this.catalogPathBuilder; Product product = new Product(); product.Id = o.Id; product.UrlSegment = o.UrlSegment; // ISSUE: variable of the null type dynamic local = null; autocompleteItemResult.Url = catalogPathBuilder.MakeCanonicalProductUrlPath(product, (Language)local); if (unitOfWork.GetTypedRepository <IProductRepository>().Get((Guid)o.Id).Unspsc != null) { autocompleteItemResult.Properties["Unspsc"] = unitOfWork.GetTypedRepository <IProductRepository>().Get((Guid)o.Id).Unspsc; } else { autocompleteItemResult.Properties["Unspsc"] = string.Empty; } return(autocompleteItemResult); })).ToList <GetProductAutocompleteItemResult>(); return(this.NextHandler.Execute(unitOfWork, parameter, result)); }
public async Task <ProductSearchResult> GetProductsByNameSearch(SearchModel searchModel) { var query = _dbset.Where(x => x.ProductName.Contains(searchModel.SearchName)) .Include(x => x.Images); query = query.Include(x => x.Subcategory).Include(x => x.Subcategory.Category).OrderByDescending(x => x.DatePosted); var productSearchResult = new ProductSearchResult { TotalCount = await query.CountAsync(), Products = await query.Skip(searchModel.ItemsToSkip).Take(searchModel.ItemsPerPage).ToListAsync() }; return(productSearchResult); }
public IList <string> GetProductIds(String categoryId, int count) { String jsonResponse = JsonGetRequest(this.dwBaseUrl + "/product_search" + clientIdRequestParam + "&refine_1=cgid%3D" + categoryId + "&count=" + count); ProductSearchResult result = JsonConvert.DeserializeObject <ProductSearchResult>(jsonResponse); var products = result.hits; var productIds = new List <string>(); foreach (var product in products) { productIds.Add(product.product_id); } return(productIds); }
public virtual ProductSearchResult SearchItems(string scope, ISearchCriteria criteria, ItemResponseGroup responseGroup) { var result = new ProductSearchResult(); var searchResults = _searchProvider.Search <DocumentDictionary>(scope, criteria); if (searchResults != null) { var returnProductsFromIndex = _settingsManager.GetValue("VirtoCommerce.SearchApi.UseFullObjectIndexStoring", true); result.TotalCount = searchResults.TotalCount; result.Aggregations = ConvertFacetsToAggregations(searchResults.Facets, criteria); result.Products = ConvertDocumentsToProducts(searchResults.Documents?.ToList(), returnProductsFromIndex, criteria, responseGroup); } return(result); }
public ProductSearchResult SearchItems(CatalogIndexedSearchCriteria criteria, moduleModel.ItemResponseGroup responseGroup = moduleModel.ItemResponseGroup.ItemSmall) { CatalogItemSearchResults results; var items = Search(criteria, out results, responseGroup); var catalogItems = new List <Product>(); // go through items foreach (var item in items) { var searchTags = results.Items[item.Id.ToLower()]; var currentOutline = this.GetItemOutlineUsingContext( searchTags[criteria.OutlineField].ToString(), criteria.Catalog); var catalogItem = item.ToWebModel(_blobUrlResolver) as Product; catalogItem.Outline = this.StripCatalogFromOutline(currentOutline, criteria.Catalog); int reviewTotal; if (searchTags.ContainsKey(criteria.ReviewsTotalField) && int.TryParse(searchTags[criteria.ReviewsTotalField].ToString(), out reviewTotal)) { catalogItem.ReviewsTotal = reviewTotal; } double reviewAvg; if (searchTags.ContainsKey(criteria.ReviewsAverageField) && double.TryParse(searchTags[criteria.ReviewsAverageField].ToString(), out reviewAvg)) { catalogItem.Rating = reviewAvg; } catalogItems.Add(catalogItem); } var response = new ProductSearchResult(); response.Items.AddRange(catalogItems); response.TotalCount = results.TotalCount; //TODO need better way to find applied filter values var appliedFilters = criteria.CurrentFilters.SelectMany(x => x.GetValues()).Select(x => x.Id).ToArray(); response.Facets = results.FacetGroups == null ? null : results.FacetGroups.Select(g => g.ToWebModel(appliedFilters)).ToArray(); return(response); }
public ProductSearchResult SearchItems(CatalogIndexedSearchCriteria criteria, moduleModel.ItemResponseGroup responseGroup = moduleModel.ItemResponseGroup.ItemSmall) { CatalogItemSearchResults results; var items = Search(criteria, out results, responseGroup); var catalogItems = new List<Product>(); // go through items foreach (var item in items) { var searchTags = results.Items[item.Id.ToLower()]; var currentOutline = this.GetItemOutlineUsingContext( searchTags[criteria.OutlineField].ToString(), criteria.Catalog); var catalogItem = item.ToWebModel(_blobUrlResolver) as Product; catalogItem.Outline = this.StripCatalogFromOutline(currentOutline, criteria.Catalog); int reviewTotal; if (searchTags.ContainsKey(criteria.ReviewsTotalField) && int.TryParse(searchTags[criteria.ReviewsTotalField].ToString(), out reviewTotal)) { catalogItem.ReviewsTotal = reviewTotal; } double reviewAvg; if (searchTags.ContainsKey(criteria.ReviewsAverageField) && double.TryParse(searchTags[criteria.ReviewsAverageField].ToString(), out reviewAvg)) { catalogItem.Rating = reviewAvg; } catalogItems.Add(catalogItem); } var response = new ProductSearchResult(); response.Items.AddRange(catalogItems); response.TotalCount = results.TotalCount; //TODO need better way to find applied filter values var appliedFilters = criteria.CurrentFilters.SelectMany(x => x.GetValues()).Select(x => x.Id).ToArray(); response.Facets = results.FacetGroups == null ? null : results.FacetGroups.Select(g => g.ToWebModel(appliedFilters)).ToArray(); return response; }
private static void ExtractStringAggregation(ProductSearchResult result, KeyValuePair <string, IAggregate> y) { var agg = new Dictionary <string, long>(); foreach (var bucket in ((Nest.BucketAggregate)y.Value).Items) { if (bucket.GetType() != typeof(KeyedBucket <object>)) { continue; } var docCount = ((KeyedBucket <object>)bucket).DocCount; if (docCount == null) { continue; } agg.Add((string)((KeyedBucket <object>)bucket).Key, docCount.Value); } result.StringAggregations.Add(y.Key, agg); }
protected virtual IList <Facet> BuildFacets(SearchCriteria criteria, ProductSearchResult searchResult) { if (searchResult.Facets == null) { return(new List <Facet>()); } var cultureInfo = criteria.CultureInfo; var selectedFacets = criteria.SelectedFacets; var facetList = searchResult.Facets .Select(facetResult => FacetFactory.CreateFacet(facetResult, selectedFacets, cultureInfo)) .Where(facet => facet != null && facet.Quantity > 0) .OrderBy(facet => facet.SortWeight) .ThenBy(facet => facet.FieldName) .ToList(); return(facetList); }
public async Task <ProductSearchResult> GetApiModelListAsync(int?hotSale, string keyword, int pageIndex, int pageSize) { using (MyDbContext dbc = new MyDbContext()) { ProductSearchResult result = new ProductSearchResult(); var entities = dbc.GetAll <ProductEntity>().AsNoTracking().Where(p => p.Putaway == 1); if (hotSale != null) { entities = entities.Where(a => a.HotSale == hotSale); } if (!string.IsNullOrEmpty(keyword)) { entities = entities.Where(a => a.Name.Contains(keyword)); } result.PageCount = (int)Math.Ceiling((await entities.LongCountAsync()) * 1.0f / pageSize); var res = await entities.OrderByDescending(a => a.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); result.List = res.Select(a => ToApiDTO(a)).ToArray(); return(result); } }