private IOrderedQueryable<Book> SortDecending( IOrderedQueryable<Book> books) { IOrderedQueryable<Book> orderedBooks = books.OrderByDescending(b => b.Title); return orderedBooks; }
private IOrderedQueryable<Book> Sort( IOrderedQueryable<Book> books) { IOrderedQueryable<Book> orderedBooks = books.OrderBy(b => b.Title); return orderedBooks; }
public NavBarItemManagerAdminViewModel(StoreFrontConfiguration storeFrontConfig, UserProfile userProfile, IOrderedQueryable<NavBarItem> navBarItems) : base(storeFrontConfig, userProfile) { this.NavBarItems = navBarItems; if (navBarItems != null) { this.NavBarItemEditViewModels = navBarItems.Select(nb => new NavBarItemEditAdminViewModel(nb, userProfile)).ToList(); } }
private void LoadUnassignedIncidents() { var unassignedIncidents = from incident in techSupport.SQLIncidents where incident.TechID.HasValue == false orderby incident.DateOpened descending select incident; incidentList = unassignedIncidents; sQLIncidentBindingSource.DataSource = incidentList; }
private static IQueryable<DashboardRoundDisplay> BuildSelectStatement(ToracGolfContext dbContext, IOrderedQueryable<Round> sortedQuery) { return sortedQuery.Take(5).Select(x => new DashboardRoundDisplay { CourseId = x.Course.CourseId, RoundDate = x.RoundDate, Score = x.Score, CourseName = x.Course.Name, TeeBoxLocation = dbContext.CourseTeeLocations.FirstOrDefault(y => y.CourseTeeLocationId == x.CourseTeeLocationId).Description }); }
private void DeserializeFoundReviews(IOrderedQueryable<Review> reviewsInPeriod, IList<FoundReviewTransferObject> reviewsFound) { foreach (Review review in reviewsInPeriod) { FoundReviewTransferObject foundReview = new FoundReviewTransferObject(); foundReview.Date = review.DateOfCreation; foundReview.Content = review.Content; foundReview.BookTitle = review.Book.Title; foundReview.BookIsbn = review.Book.ISBN; foundReview.BookUrl = review.Book.WebSite; if (review.Book.Authors.Count != 0) { var authorNames = review.Book.Authors .OrderBy(a => a.Name).Select(a => a.Name); foundReview.BookAuthors = string.Join(", ", authorNames); } reviewsFound.Add(foundReview); } }
protected void Page_Load(object sender, EventArgs e) { if (String.IsNullOrEmpty(Request.QueryString["subid"])) { //PROTEGEES int id = Convert.ToInt32(Request.QueryString["id"]); images = LinqGetProtegees(id); //SETTING THUMBNAILS LINK hl_thumbnails.NavigateUrl = "~/Thumbnails.aspx?id=" + Request.QueryString["id"]; } else { //SUBCELLS int id = Convert.ToInt32(Request.QueryString["subid"]); images = LinqGetSubcells(id); //SETTING THUMBNAILS LINK hl_thumbnails.NavigateUrl = "~/Thumbnails.aspx?id=" + Request.QueryString["id"] + "&subid=" + Request.QueryString["subid"]; } //GENERATE IMAGES TO PRELOAD foreach(var image in images) { js += "\tImages[" + iterator + "] = new Image(750, 500).src = \"Admin/_dynimg/Image/" + image.image_id + ".jpg\";\n"; iterator++; } js = string.Format(SCRIPT_TEMPLATE, js); if (images.FirstOrDefault() != null) { main_image.ImageUrl = "~/Admin/_dynimg/Image/" + images.FirstOrDefault().image_id + ".jpg"; } //SETTING CURRENT PAGER || FROM THUMBNAILS if(!String.IsNullOrEmpty(Request.QueryString["pid"])) { evil_pager = "var pager = " + Request.QueryString["pid"] + ";"; } //SETTING CREDITS GetCredits(); }
/// <summary> /// Filtering the employees by entered search word /// </summary> /// <param name="search">The word that you want to filter the employees by</param> /// <param name="employees">Collection of employees that will be filtered</param> /// <returns>The input collection filtered</returns> private IOrderedQueryable<Employee> FilterEmployees(string search, IOrderedQueryable<Employee> employees) { if (!String.IsNullOrEmpty(search)) { employees = employees.Where(e => e.Fields.FirstName.Contains(search) || e.Fields.Position.ToString().Contains(search) || e.Fields.LastName.Contains(search) || e.Fields.Email.Contains(search)) .OrderBy(e => e.Fields.ID); } return employees; }
public static IOrderedQueryable <T> ThenByDescending <T>(this IOrderedQueryable <T> source, string propertyName) => ApplyOrder(source, propertyName, nameof(ThenByDescending));
protected override IOrderedQueryable <TBo> ThenOrderDescByCol(IOrderedQueryable <TBo> tab) { return(tab.ThenByDescending(_ColSelector)); }
private void UpdateArticleChoiseDropDown(IOrderedQueryable<vProductAndDescripttionExtendedENOnly> products, vProductAndDescripttionExtendedENOnly activeProduct) { if (ddlArticleChoises.Items.Count == 0) { foreach (var product in products) { ddlArticleChoises.Items.Add( new ListItem( $"{(product.Size != null ? $"Size {product.Size} " : string.Empty)}{(product.Color ?? string.Empty)}", product.ProductID.ToString())); } } ddlArticleChoises.SelectedValue = activeProduct.ProductID.ToString(); panelArticleOptions.Visible = true; }
public void UpdateSortedBlogs(IOrderedQueryable<Blog> sortedBlogs) { _blogs = sortedBlogs.ToList(); }
public virtual async Task<PagedCollection<MovementDto>> FormatResult(IPagedQuery query, IOrderedQueryable<Movement> movements) { return await movements.Map().ToPagedCollectionAsync(query); }
public static IOrderedCacheOptimizedQueryable <TSource> AsOrderedCacheOptimizedQueryable <TSource>( this IOrderedQueryable <TSource> originalQueryable) { return(new OrderedCacheOptimizedQueryable <TSource>(originalQueryable)); }
/// <summary> /// 对IOrderedQueryable进行分页 /// </summary> /// <typeparam name="TSource">实体类</typeparam> /// <param name="source">List列表</param> /// <param name="pageSize">每页大小</param> /// <param name="pageIndex">索引</param> public static List <TSource> ToList <TSource>(this IOrderedQueryable <TSource> source, int pageSize, int pageIndex = 1) { return(source.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList()); }
/// <summary> /// 进行搜索 /// </summary> public virtual void DoSearch() { var cmd = GetSearchCommand(); if (cmd == null) { IOrderedQueryable <TModel> query = null; //根据搜索模式调用不同的函数 switch (SearcherMode) { case ListVMSearchModeEnum.Search: query = GetSearchQuery(); break; case ListVMSearchModeEnum.Export: query = GetExportQuery(); break; case ListVMSearchModeEnum.Batch: query = GetBatchQuery(); break; case ListVMSearchModeEnum.MasterDetail: query = GetMasterDetailsQuery(); break; case ListVMSearchModeEnum.CheckExport: query = GetCheckedExportQuery(); break; case ListVMSearchModeEnum.Selector: query = GetSelectorQuery(); break; default: query = GetSearchQuery(); break; } //如果设定了替换条件,则使用替换条件替换Query中的Where语句 if (ReplaceWhere != null) { var mod = new WhereReplaceModifier <TopBasePoco>(ReplaceWhere); var newExp = mod.Modify(query.Expression); query = query.Provider.CreateQuery <TModel>(newExp) as IOrderedQueryable <TModel>; } if (Searcher.SortInfo != null) { var mod = new OrderReplaceModifier(Searcher.SortInfo); var newExp = mod.Modify(query.Expression); query = query.Provider.CreateQuery <TModel>(newExp) as IOrderedQueryable <TModel>; } if (typeof(TModel).IsSubclassOf(typeof(PersistPoco))) { var mod = new IsValidModifier(); var newExp = mod.Modify(query.Expression); query = query.Provider.CreateQuery <TModel>(newExp) as IOrderedQueryable <TModel>; } if (PassSearch == false) { //如果需要分页,则添加分页语句 if (NeedPage && Searcher.Limit != -1) { //获取返回数据的数量 var count = query.Count(); if (count < 0) { count = 0; } if (Searcher.Limit == 0) { Searcher.Limit = ConfigInfo?.UiOptions.DataTable.RPP ?? 20; } //根据返回数据的数量,以及预先设定的每页行数来设定数据量和总页数 Searcher.Count = count; Searcher.PageCount = (int)Math.Ceiling((1.0 * Searcher.Count / Searcher.Limit)); if (Searcher.Page <= 0) { Searcher.Page = 1; } if (Searcher.PageCount > 0 && Searcher.Page > Searcher.PageCount) { Searcher.Page = Searcher.PageCount; } EntityList = query.Skip((Searcher.Page - 1) * Searcher.Limit).Take(Searcher.Limit).AsNoTracking().ToList(); } else //如果不需要分页则直接获取数据 { EntityList = query.AsNoTracking().ToList(); Searcher.Count = EntityList.Count(); Searcher.Limit = EntityList.Count(); Searcher.PageCount = 1; Searcher.Page = 1; } } else { EntityList = query.AsNoTracking().ToList(); } } else { ProcessCommand(cmd); } IsSearched = true; //调用AfterDoSearch函数来处理自定义的后续操作 AfterDoSearcher(); }
/// <summary> /// Order then by the string expression provided. /// </summary> /// <param name="query">The IOrderedQueryable to add additional sorting to.</param> /// <param name="propertyName">The path to the property to order by (e.g. Path.To.Property).</param> /// <param name="direction">Order by which to sort items.</param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IOrderedQueryable <T> ThenBy <T>(this IOrderedQueryable <T> query, string propertyName, OrderByDirection direction = OrderByDirection.Ascending) => query.AppendOrderByExpression(propertyName, direction, true);
public static IOrderedQueryable <TEntity> ThenByDescending <TEntity>(this IOrderedQueryable <TEntity> source, string fieldName) where TEntity : class { MethodCallExpression resultExp = GenerateMethodCall <TEntity>(source, "ThenByDescending", fieldName); return(source.Provider.CreateQuery <TEntity>(resultExp) as IOrderedQueryable <TEntity>); }
/// <summary> /// Orders the query by a field name with direction based on a flag. /// </summary> /// <param name="source">The sequence of values.</param> /// <param name="propName">Name of the property to use for sorting.</param> /// <param name="isDescending">Order direction flag.</param> public static IOrderedQueryable <T> ThenBy <T>(this IOrderedQueryable <T> source, string propName, bool isDescending) { var method = isDescending ? OrderMethods.ThenByDescending : OrderMethods.ThenBy; return(OrderByInternal(source, propName, method)); }
/// <summary> /// Orders the query by a field with direction based on a flag. /// </summary> /// <param name="source">The sequence of values.</param> /// <param name="orderExpr">Descriptor of the property to use for sorting.</param> /// <param name="isDescending">Order direction flag.</param> public static IOrderedQueryable <T> ThenBy <T, T2>(this IOrderedQueryable <T> source, Expression <Func <T, T2> > orderExpr, bool isDescending) { return(isDescending ? source.ThenByDescending(orderExpr) : source.ThenBy(orderExpr)); }
public static IOrderedQueryable <T> ThenByDescendingInternal <T, TProp>(IOrderedQueryable <T> query, PropertyInfo memberProperty) {//public return(query.ThenByDescending(_GetLamba <T, TProp>(memberProperty))); }
// Ordering method by some criteria private IOrderedQueryable<Employee> OrderEmployees(string sortOrder, IOrderedQueryable<Employee> employees) { ViewBag.NameSort = String.IsNullOrEmpty(sortOrder) ? "name" : ""; ViewBag.PositionSort = String.IsNullOrEmpty(sortOrder) ? "position" : ""; ViewBag.ProjectSort = String.IsNullOrEmpty(sortOrder) ? "project" : ""; ViewBag.TeamSort = String.IsNullOrEmpty(sortOrder) ? "team" : ""; ViewBag.WorkplaceSort = String.IsNullOrEmpty(sortOrder) ? "workplace" : ""; switch (sortOrder) { case "name": employees = employees.OrderBy(e => e.Name); break; case "position": employees = employees.OrderBy(e => e.Position.ToString()); break; case "project": employees = employees.OrderBy(e => e.Project.ProjectName); break; case "team": employees = employees.OrderBy(e => e.Team.Name); break; case "workplace": employees = employees.OrderBy(e => e.Workplace); break; default: employees = employees.OrderBy(e => e.Id); break; } return employees; }
public static IOrderedCacheOptimizedQueryable <TSource> AsOrderedCacheOptimizedQueryable <TSource>( this IOrderedQueryable <TSource> originalQueryable, IOptimizationConfig optimizationConfig) { return(new OrderedCacheOptimizedQueryable <TSource>(originalQueryable, optimizationConfig)); }
internal YacqOrderedQueryable(SymbolTable symbols, IOrderedQueryable source) : base(symbols, source) { this._source = source; }
/// <summary> /// Sorts the results. /// </summary> /// <param name="items">The items.</param> /// <returns></returns> private IQueryable <ContentChannelItem> SortResults(IQueryable <ContentChannelItem> items) { SortProperty sortProperty = null; string orderBy = GetAttributeValue("Order"); if (!string.IsNullOrWhiteSpace(orderBy)) { var fieldDirection = new List <string>(); var orderByPairs = orderBy.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries) .Select(a => a.Split('^')); foreach (var itemPair in orderByPairs) { if (itemPair.Length == 2 && !string.IsNullOrWhiteSpace(itemPair[0])) { var sortDirection = SortDirection.Ascending; if (!string.IsNullOrWhiteSpace(itemPair[1])) { sortDirection = itemPair[1].ConvertToEnum <SortDirection>(SortDirection.Ascending); } fieldDirection.Add(itemPair[0] + (sortDirection == SortDirection.Descending ? " desc" : "")); } } sortProperty = new SortProperty { Direction = SortDirection.Ascending, Property = fieldDirection.AsDelimited(",") }; string[] columns = sortProperty.Property.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); IOrderedQueryable <ContentChannelItem> orderedQry = null; for (int columnIndex = 0; columnIndex < columns.Length; columnIndex++) { string column = columns[columnIndex].Trim(); var direction = sortProperty.Direction; if (column.ToLower().EndsWith(" desc")) { column = column.Left(column.Length - 5); direction = sortProperty.Direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending; } try { if (column.StartsWith("Attribute:")) { string attributeKey = column.Substring(10); if (direction == SortDirection.Ascending) { orderedQry = (columnIndex == 0) ? items.OrderBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) : orderedQry.ThenBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue); } else { orderedQry = (columnIndex == 0) ? items.OrderByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) : orderedQry.ThenByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue); } } else { if (direction == SortDirection.Ascending) { orderedQry = (columnIndex == 0) ? items.OrderBy(column) : orderedQry.ThenBy(column); } else { orderedQry = (columnIndex == 0) ? items.OrderByDescending(column) : orderedQry.ThenByDescending(column); } } } catch { } } try { if (orderedQry != null) { return(orderedQry); } } catch { } } // If we got here we did not have any sort requested, add a default by start date so pagination will work return(items.OrderByDescending(i => i.StartDateTime)); }
public WebFormManagerAdminViewModel(StoreFrontConfiguration storeFrontConfig, UserProfile userProfile, IOrderedQueryable<WebForm> webForms) : base(storeFrontConfig, userProfile) { this.WebForms = webForms; }
public static IQueryable <T> Page <T>(this IOrderedQueryable <T> source, IPageRequest request) { return(source .Skip(request.GetSkip()) .Take(request.PageSize)); }
private void GetBlogs(IOrderedQueryable<Blog> query) { Blogs = new List<Blog>(); BlogNames = new List<string>(); foreach (var item in query) { Blogs.Add(item); BlogNames.Add(item.Name); } }
private IOrderedQueryable <E> SortNext(string name, IOrderedQueryable <E> source) { return(nextPasses[name].Invoke(source)); }
public ValueListManagerAdminViewModel(StoreFrontConfiguration storeFrontConfig, UserProfile userProfile, IOrderedQueryable<ValueList> valueLists) : base(storeFrontConfig, userProfile) { this.ValueLists = valueLists; }
/// <summary> /// Performs a subsequent ordering of the elements in a sequence in descending order by their Elasticsearch score. /// </summary> /// <returns> /// An <see cref="T:System.Linq.IOrderedQueryable`1"/> whose elements are sorted according to score. /// </returns> /// <param name="source">A sequence of values to order.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="source"/> is null.</exception> public static IOrderedQueryable <TSource> ThenByScoreDescending <TSource>(this IOrderedQueryable <TSource> source) { return((IOrderedQueryable <TSource>)CreateQueryMethodCall(source, thenByScoreDescendingMethodInfo)); }
public static IOrderedQueryable <TSource> ThenByDescending <TSource, TKey>(this IOrderedQueryable <TSource> source, Expression <Func <TSource, TKey> > keySelector, IComparer <TKey> comparer) { Check.SourceAndKeySelector(source, keySelector); return((IOrderedQueryable <TSource>)source.Provider.CreateQuery(StaticCall(MakeGeneric(MethodBase.GetCurrentMethod(), typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer)))); }
public static IOrderedQueryable <T> Sort <T>(this IQueryable <T> baseQuery, string sortInfo, params SortInfo[] defaultSorts) where T : TopBasePoco { List <SortInfo> info = new List <SortInfo>(); IOrderedQueryable <T> rv = null; if (string.IsNullOrEmpty(sortInfo)) { if (defaultSorts == null || defaultSorts.Length == 0) { ParameterExpression pe = Expression.Parameter(typeof(T)); var idproperty = typeof(T).GetProperties().Where(x => x.Name.ToLower() == "id").FirstOrDefault(); Expression pro = Expression.Property(pe, idproperty); Type proType = typeof(Guid); Expression final = Expression.Call( typeof(Queryable), "OrderBy", new Type[] { typeof(T), proType }, baseQuery.Expression, Expression.Lambda(pro, new ParameterExpression[] { pe })); rv = baseQuery.Provider.CreateQuery <T>(final) as IOrderedQueryable <T>; return(rv); } else { info.AddRange(defaultSorts); } } else { var temp = APIHelper.JsonDeserialize <List <SortInfo> >(sortInfo); info.AddRange(temp); } foreach (var item in info) { ParameterExpression pe = Expression.Parameter(typeof(T)); var idproperty = typeof(T).GetProperties().Where(x => x.Name == item.Property).FirstOrDefault(); Expression pro = Expression.Property(pe, idproperty); Type proType = typeof(T).GetProperty(item.Property).PropertyType; if (item.Direction == SortDir.Asc) { if (rv == null) { Expression final = Expression.Call( typeof(Queryable), "OrderBy", new Type[] { typeof(T), proType }, baseQuery.Expression, Expression.Lambda(pro, new ParameterExpression[] { pe })); rv = baseQuery.Provider.CreateQuery <T>(final) as IOrderedQueryable <T>; } else { Expression final = Expression.Call( typeof(Queryable), "ThenBy", new Type[] { typeof(T), proType }, rv.Expression, Expression.Lambda(pro, new ParameterExpression[] { pe })); rv = rv.Provider.CreateQuery <T>(final) as IOrderedQueryable <T>; } } if (item.Direction == SortDir.Desc) { if (rv == null) { Expression final = Expression.Call( typeof(Queryable), "OrderByDescending", new Type[] { typeof(T), proType }, baseQuery.Expression, Expression.Lambda(pro, new ParameterExpression[] { pe })); rv = baseQuery.Provider.CreateQuery <T>(final) as IOrderedQueryable <T>; } else { Expression final = Expression.Call( typeof(Queryable), "ThenByDescending", new Type[] { typeof(T), proType }, rv.Expression, Expression.Lambda(pro, new ParameterExpression[] { pe })); rv = rv.Provider.CreateQuery <T>(final) as IOrderedQueryable <T>; } } } return(rv); }
public AdminModule(IUserRepository readOnlyRepository, IMapper mapper, ICommandDispatcher commandDispatcher, IUserSessionFactory userSessionFactory) { Get["/users", true] = async(a, c) => { this.RequiresClaims(new[] { "Administrator" }); var request = this.Bind <AdminUsersRequest>(); ParameterExpression parameter = Expression.Parameter(typeof(User), "User"); Expression <Func <User, object> > mySortExpression = Expression.Lambda <Func <User, object> >(Expression.Property(parameter, request.Field), parameter); IQueryable <User> users = (await readOnlyRepository.Query <User>(x => x.Name != Context.CurrentUser.UserName)) .AsQueryable(); IOrderedQueryable <User> orderedUsers = users.OrderBy(mySortExpression); IQueryable <User> pagedUsers = orderedUsers.Skip(request.PageSize * (request.PageNumber - 1)).Take(request.PageSize); List <AdminUserResponse> usersList = mapper .Map <IQueryable <User>, IEnumerable <AdminUserResponse> >(pagedUsers).ToList(); return(usersList); }; Put["/users/{userId:guid}/enable", true] = async(p, c) => { this.RequiresClaims(new[] { "Administrator" }); Guid userId = Guid.Parse((string)p.userId); await commandDispatcher.Dispatch(userSessionFactory.Create(Context.CurrentUser), new EnableUser(userId)); return(null); }; Put["/users/{userId:guid}/disable", true] = async(p, c) => { this.RequiresClaims(new[] { "Administrator" }); Guid userId = Guid.Parse((string)p.userId); await commandDispatcher.Dispatch(userSessionFactory.Create(Context.CurrentUser), new DisableUser(userId)); return(null); }; Get["/users/{userId:guid}", true] = async(p, c) => { this.RequiresClaims(new[] { "Administrator" }); Guid userId = Guid.Parse((string)p.userId); User user = await readOnlyRepository.GetById <User>(userId); AdminUserResponse mappedUser = mapper .Map <User, AdminUserResponse>(user); return(mappedUser); }; Put["/users/{userId:guid}", true] = async(p, c) => { this.RequiresClaims(new[] { "Administrator" }); var request = this.Bind <AdminUpdateUserRequest>(); Guid userId = Guid.Parse((string)p.userId); await commandDispatcher.Dispatch(userSessionFactory.Create(Context.CurrentUser), new UpdateUserProfile(userId, request.Name, request.Email)); return(null); }; }
/// <summary> /// Add Program Package Version To the Database via Entityframework. /// The Program package version is allways linked to a Program package. /// </summary> /// <param name="queryProgram"></param> /// <param name="db"></param> /// <param name="val"></param> private static void AddProgramPackageVersionToDatabase(IOrderedQueryable<EF_Program> queryProgram, ProgramContext db, XMLClasses.feedEntry val) { var program = queryProgram.First(); db.ProgramVersions.Add(new EF_ProgramVersion {Program = program, Version = val.properties.Version}); }
/// <summary> /// Wraps a <see cref="RealmResults{T}" /> in an implementation of <see cref="INotifyCollectionChanged" /> so that it may be used in MVVM databinding. /// </summary> /// <param name="results">The <see cref="RealmResults{T}"/ > to observe for changes.</param> /// <param name="errorCallback">An error callback that will be invoked if the observing thread raises an error.</param> /// <returns>An <see cref="ObservableCollection{T}" />-like object useful for MVVM databinding.</returns> /// <seealso cref="RealmResults{T}.SubscribeForNotifications(RealmResults{T}.NotificationCallback)"/> public static INotifyCollectionChanged ToNotifyCollectionChanged <T>(this IOrderedQueryable <T> results, Action <Exception> errorCallback) where T : RealmObject { return(ToNotifyCollectionChanged(results, errorCallback, coalesceMultipleChangesIntoReset: false)); }
public static IOrderedQueryable <T> ThenByDescending <T>(this IOrderedQueryable <T> query, string propertyName) { return(_ThenBy <T>(query, propertyName, true)); }
internal static EventViewModel[] AddImagesToOurEvents(IOrderedQueryable<Event> events) { var eventIds = events.Select(e => e.Id).ToArray(); var eventViews = events.Select(EventViewModel.ViewModel).ToArray(); //TODO: Change if implementing multiple image display var eventImages = (from e in events select e.EventImages.FirstOrDefault()).ToArray(); for (int i = 0; i < eventViews.Length; i++) { if (eventImages[i] != null) eventViews[i].ImageURI = "http://localhost:9999/EventImages/Event_" + eventIds[i].ToString() + "/" + eventImages[i].ImageName; else eventViews[i].ImageURI = "http://localhost:9999/EventImages/Default/img.jpg"; } return eventViews; }
public static IOrderedQueryable <T> ThenBy <T>(this IOrderedQueryable <T> source, string propertyName) { return(OrderingHelper(source, propertyName, false, true)); }
// Searching method by criteria private static IOrderedQueryable<Employee> SearchEmployees(string search, IOrderedQueryable<Employee> employees) { if (!String.IsNullOrEmpty(search)) { employees = employees.Where(e => e.Name.Contains(search) || e.Position.ToString().Contains(search) || e.Team.Name.Contains(search) || e.Project.ProjectName.Contains(search) || e.Workplace.Contains(search)) .OrderBy(e => e.Project.ProjectName); } return employees; }
/// <summary> /// Sorts the object by the specified sort property. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="sortProperty">The sort property.</param> /// <returns></returns> public static IOrderedQueryable <T> Sort <T>(this IQueryable <T> source, Rock.Web.UI.Controls.SortProperty sortProperty) { if (sortProperty.Property.StartsWith("attribute:")) { var itemType = typeof(T); var attributeCache = AttributeCache.Read(sortProperty.Property.Substring(10).AsInteger()); if (attributeCache != null && typeof(IModel).IsAssignableFrom(typeof(T))) { var entityIds = new List <int>(); var models = new List <IModel>(); source.ToList().ForEach(i => models.Add(i as IModel)); var ids = models.Select(m => m.Id).ToList(); var field = attributeCache.FieldType.Field; using (var rockContext = new RockContext()) { foreach (var attributeValue in new AttributeValueService(rockContext) .Queryable().AsNoTracking() .Where(v => v.AttributeId == attributeCache.Id && v.EntityId.HasValue && ids.Contains(v.EntityId.Value)) .ToList()) { var model = models.FirstOrDefault(m => m.Id == attributeValue.EntityId.Value); if (model != null) { model.CustomSortValue = field.SortValue(null, attributeValue.Value, attributeCache.QualifierValues); } } } var result = new List <T>(); if (sortProperty.Direction == SortDirection.Ascending) { models.OrderBy(m => m.CustomSortValue).ToList().ForEach(m => result.Add((T)m)); } else { models.OrderByDescending(m => m.CustomSortValue).ToList().ForEach(m => result.Add((T)m)); } return(result.AsQueryable().OrderBy(r => 0)); } } string[] columns = sortProperty.Property.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); IOrderedQueryable <T> qry = null; for (int columnIndex = 0; columnIndex < columns.Length; columnIndex++) { string column = columns[columnIndex].Trim(); var direction = sortProperty.Direction; if (column.ToLower().EndsWith(" desc")) { column = column.Left(column.Length - 5); direction = sortProperty.Direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending; } if (direction == SortDirection.Ascending) { qry = (columnIndex == 0) ? source.OrderBy(column) : qry.ThenBy(column); } else { qry = (columnIndex == 0) ? source.OrderByDescending(column) : qry.ThenByDescending(column); } } return(qry); }
//------------------------------------------------------------------------------------------- private void PopulateTree(WeavverEntityContainer data, TreeNode parentNode, IOrderedQueryable<Weavver.Data.KnowledgeBase> items) { foreach (var article in items.ToList()) { TreeNode node = new TreeNode(article.Title, article.Id.ToString()); if (parentNode == null) Navigation.Nodes.Add(node); else parentNode.ChildNodes.Add(node); //if (article.KnowledgeBase2Reference.HasValue) //{ var childItems = from childArticles in data.KnowledgeBase where childArticles.ParentId == article.Id && article.OrganizationId == SelectedOrganization.Id orderby childArticles.Position, childArticles.Title select childArticles; PopulateTree(data, node, childItems); //} } }
public static async Task <PagedList <T> > PaginateAsync(int pageNumber, int pageSize, IOrderedQueryable <T> collection) { int totalCount = await collection.CountAsync(); List <T> pagedList = await collection.Skip((pageNumber - 1) *pageSize).Take(pageSize).ToListAsync(); return(new PagedList <T>(pagedList, totalCount)); }
private ActionResult ShowRecords(int id, IOrderedQueryable<RecordListViewModel> recordsListViewModel) { var area = this.areas.GetById(id); var areaViewModel = Mapper.Map<AreaDetailsViewModel>(area); var areaManageViewModel = new AreaManageViewModel { Area = areaViewModel, Records = recordsListViewModel }; return View("Manage", areaManageViewModel); }
public IEnumerable <T> GetPagedList(out int totalCount, int?page = null, int?pageSize = null, Expression <Func <T, bool> > filter = null, string[] includePaths = null, params SortExpression <T>[] sortExpressions) { IQueryable <T> query = _dbSet; if (filter != null) { query = _dbSet.Where(filter); } totalCount = query.Count(); if (includePaths != null) { for (var i = 0; i < includePaths.Count(); i++) { query = query.Include(includePaths[i]); } } if (sortExpressions != null) { IOrderedQueryable <T> orderedQuery = null; for (var i = 0; i < sortExpressions.Count(); i++) { if (i == 0) { if (sortExpressions[i].SortDirection == ListSortDirection.Ascending) { orderedQuery = query.OrderBy(sortExpressions[i].SortBy); } else { orderedQuery = query.OrderByDescending(sortExpressions[i].SortBy); } } else { if (sortExpressions[i].SortDirection == ListSortDirection.Ascending) { orderedQuery = orderedQuery.ThenBy(sortExpressions[i].SortBy); } else { orderedQuery = orderedQuery.ThenByDescending(sortExpressions[i].SortBy); } } } if (page != null) { query = orderedQuery.Skip(((int)page - 1) * (int)pageSize); } } if (pageSize != null) { query = query.Take((int)pageSize); } return(query.ToList()); }
/// <summary> /// Create from collection for the base type Record, the lookup /// list of datasets, and IOrderedQueryable(TRecord). /// /// This constructor is private and is intended for use by the /// implementation of this class only. /// </summary> private TemporalMongoQuery(TemporalMongoCollection <TRecord> collection, TemporalId loadFrom, IOrderedQueryable <TRecord> orderedQueryable) { if (orderedQueryable == null) { throw new Exception( "Attempting to create a query from a null orderedQueryable."); } collection_ = collection; loadFrom_ = loadFrom; orderedQueryable_ = orderedQueryable; }
public void NullSourceComparer() { IOrderedQueryable <int> source = null; Assert.Throws <ArgumentNullException>("source", () => source.ThenBy(i => i, null)); }
public Series CreateSeries(string name, IOrderedQueryable<Item> items, Func<Item, float> selector, Color color) { Series seriesDetail = new Series(); SeriesChartType chartType = SeriesChartType.Line; seriesDetail.Name = name; seriesDetail.IsValueShownAsLabel = false; seriesDetail.Color = color; seriesDetail.ChartType = chartType; seriesDetail.BorderWidth = 2; DataPoint point; foreach (Item item in items) { point = new DataPoint(); point.AxisLabel = item.Timestamp.ToShortDateString(); point.YValues = new double[] { (double) selector(item) }; seriesDetail.Points.Add(point); } seriesDetail.ChartArea = name; return seriesDetail; }
public static IOrderedQueryable <T> ThenByDescending <T>(this IOrderedQueryable <T> source, string property) { return(ApplyOrder <T>(source, property, "ThenByDescending")); }
public void UpdateSortedBlogEntries(IOrderedQueryable<Blog> sortedBlogEntries) { _blogEntries = _blogEntries.ToList(); }
public void UpdateSortedProductBundles(IOrderedQueryable<ProductBundle> sortedProductBundles) { _productBundles = sortedProductBundles.ToList(); }
public bool InitBlog() { using (var db = new BloggingContext()) { // For adding to a specific blog _Blogs = from blogs in db.Blogs orderby blogs.Name select blogs; var blog = new Blog { Name = "Personal" }; if (!BlogExists(BlogName)) { try { db.Blogs.Add(blog); db.SaveChanges(); } catch { return false; } } else { DidBlogExist = true; } return true; } }
/// <summary> /// Filtering the teams by entered search word /// </summary> /// <param name="search">The word that you want to filter the teams by</param> /// <param name="team">Collection of teams that will be filtered</param> /// <returns>The input collection filtered</returns> private IOrderedQueryable<Team> FilterTeams(string search, IOrderedQueryable<Team> team) { if (!String.IsNullOrEmpty(search)) { team = team.Where(e => e.Fields.Name.Contains(search) || e.Fields.Delivery.ToString().Contains(search) || e.Fields.AvailablePositions.Contains(search)) .OrderBy(e => e.Fields.ID); } return team; }
public PageManagerAdminViewModel(StoreFrontConfiguration storeFrontConfig, UserProfile userProfile, IOrderedQueryable<Page> pages) : base(storeFrontConfig, userProfile) { this.Pages = pages; }
/// <summary> /// Gets the query. /// </summary> /// <returns></returns> private IOrderedQueryable <FinancialBatch> GetQuery() { var batchService = new FinancialBatchService(new RockContext()); var qry = batchService.Queryable() .Where(b => b.BatchStartDateTime.HasValue); // filter by date string dateRangeValue = gfBatchFilter.GetUserPreference("Date Range"); if (!string.IsNullOrWhiteSpace(dateRangeValue)) { var drp = new DateRangePicker(); drp.DelimitedValues = dateRangeValue; if (drp.LowerValue.HasValue) { qry = qry.Where(b => b.BatchStartDateTime >= drp.LowerValue); } if (drp.UpperValue.HasValue) { var endOfDay = drp.UpperValue.Value.AddDays(1); qry = qry.Where(b => b.BatchStartDateTime < drp.UpperValue); } } // filter by status var status = gfBatchFilter.GetUserPreference("Status").ConvertToEnumOrNull <BatchStatus>(); if (status.HasValue) { qry = qry.Where(b => b.Status == status); } // filter by title string title = gfBatchFilter.GetUserPreference("Title"); if (!string.IsNullOrEmpty(title)) { qry = qry.Where(batch => batch.Name.StartsWith(title)); } // filter by accounting code if (tbAccountingCode.Visible) { string accountingCode = gfBatchFilter.GetUserPreference("Accounting Code"); if (!string.IsNullOrEmpty(accountingCode)) { qry = qry.Where(batch => batch.AccountingSystemCode.StartsWith(accountingCode)); } } // filter by campus var campus = CampusCache.Read(gfBatchFilter.GetUserPreference("Campus").AsInteger()); if (campus != null) { qry = qry.Where(b => b.CampusId == campus.Id); } IOrderedQueryable <FinancialBatch> sortedQry = null; SortProperty sortProperty = gBatchList.SortProperty; if (sortProperty != null) { switch (sortProperty.Property) { case "TransactionCount": { if (sortProperty.Direction == SortDirection.Ascending) { sortedQry = qry.OrderBy(b => b.Transactions.Count()); } else { sortedQry = qry.OrderByDescending(b => b.Transactions.Count()); } break; } case "TransactionAmount": { if (sortProperty.Direction == SortDirection.Ascending) { sortedQry = qry.OrderBy(b => b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M); } else { sortedQry = qry.OrderByDescending(b => b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M); } break; } default: { sortedQry = qry.Sort(sortProperty); break; } } } else { sortedQry = qry .OrderByDescending(b => b.BatchStartDateTime) .ThenBy(b => b.Name); } return(sortedQry); }
private void balliZaPoseshenie(int GruppaID, int DisciplinaID, int PrepodID, IOrderedQueryable <tableStudents> students) { DateTime osenNachalo = DateTime.Parse("01.09." + DateTime.Now.Year.ToString()); DateTime osenKonec = DateTime.Parse("31.12." + DateTime.Now.Year.ToString()); DateTime vesnaNachalo = DateTime.Parse("01.01." + DateTime.Now.Year.ToString()); DateTime vesnaKonec = DateTime.Parse("01.06." + DateTime.Now.Year.ToString()); DateTime pervayaAttestaciya = DateTime.Parse("07.11." + DateTime.Now.Year.ToString()); DateTime vtorayaAttestaciya = DateTime.Parse("07.03." + DateTime.Now.Year.ToString()); IEnumerable <tableZanyatiy> chisloParPervoyAttestacii; IEnumerable <tableZanyatiy> chisloParVtoroyAttestacii; if (DateTime.Now.Month >= 7 && DateTime.Now.Month <= 12) { chisloParPervoyAttestacii = from cz in contextDB.tableZanyatiy where cz.ID_Gruppi == GruppaID && cz.ID_Disciplini == DisciplinaID && cz.ID_Prepoda == PrepodID && cz.Vremya > osenNachalo && cz.Vremya < pervayaAttestaciya select cz; chisloParVtoroyAttestacii = from cz in contextDB.tableZanyatiy where cz.ID_Gruppi == GruppaID && cz.ID_Disciplini == DisciplinaID && cz.ID_Prepoda == PrepodID && cz.Vremya > pervayaAttestaciya && cz.Vremya < osenKonec select cz; } else { chisloParPervoyAttestacii = from cz in contextDB.tableZanyatiy where cz.ID_Gruppi == GruppaID && cz.ID_Disciplini == DisciplinaID && cz.ID_Prepoda == PrepodID && cz.Vremya > vesnaNachalo && cz.Vremya < vtorayaAttestaciya select cz; chisloParVtoroyAttestacii = from cz in contextDB.tableZanyatiy where cz.ID_Gruppi == GruppaID && cz.ID_Disciplini == DisciplinaID && cz.ID_Prepoda == PrepodID && cz.Vremya > vtorayaAttestaciya && cz.Vremya < vesnaKonec select cz; } foreach (var stud in students) { var chisloOtmetokPervoyAtt = //2 раза from z in chisloParPervoyAttestacii from p in contextDB.tablePoseshenie where z.ID == p.ID_Zanyatiya && p.ID_Studenta == stud.ID && p.Otmetka == 1 select p; var chisloOtmetokVtoroyAtt = //2 раза from z in chisloParVtoroyAttestacii from p in contextDB.tablePoseshenie where z.ID == p.ID_Zanyatiya && p.ID_Studenta == stud.ID && p.Otmetka == 1 select p; int pos1 = 0, pos2 = 0; if (chisloParPervoyAttestacii.Count() > 0) { pos1 = chisloOtmetokPervoyAtt.Count() * 5 / chisloParPervoyAttestacii.Count(); } if (chisloParVtoroyAttestacii.Count() > 0) { pos2 = chisloOtmetokVtoroyAtt.Count() * 10 / chisloParVtoroyAttestacii.Count(); } var StudentsPoint = (from sp in contextDB.tableBalli where sp.ID_Gruppi == GruppaID && sp.ID_Disciplini == DisciplinaID && sp.ID_prepoda == PrepodID && sp.ID_Studenta == stud.ID select sp).First(); StudentsPoint.Pos1 = pos1; StudentsPoint.Pos2 = pos2; StudentsPoint.Itog = StudentsPoint.Pos1 + StudentsPoint.Tek1 + StudentsPoint.Rub1 + StudentsPoint.Pos2 + StudentsPoint.Tek2 + StudentsPoint.Rub2 + StudentsPoint.Samost + StudentsPoint.Dosdacha + StudentsPoint.Premial; } contextDB.SaveChanges(); }
private LicenseDisplay GetLicense(ABSNowEntities context, IEnumerable<Int32> enumerable, IOrderedQueryable<LicensePurchased> licenses, int packageId) { DateTime? LicenseEndDate = null; DateTime? LicenseStartDate = null; string LicensePurchaseId = String.Empty; foreach (var item in licenses) { if (enumerable.Contains(item.PackageID)) { if (LicenseEndDate == null) { LicenseStartDate = item.LicenseStartDate; LicenseEndDate = item.LicenseEndDate; LicensePurchaseId = item.LicensePurchasedID.ToString(); } else { if (item.LicenseEndDate > LicenseEndDate) { LicenseEndDate = item.LicenseEndDate; LicenseStartDate = item.LicenseStartDate; LicensePurchaseId = item.LicensePurchasedID.ToString(); } } } } var package = context.Packages.FirstOrDefault(p => p.PackageID == packageId); if (LicenseEndDate != null) return new LicenseDisplay() { PackageId = package.PackageID, PackageName = package.PackageName, PackageDescription = package.PackageDescription, LicenseEndDate = (DateTime)LicenseEndDate, LicenseEndDateStr = ((DateTime)LicenseEndDate).ToString("MM/dd/yyyy hh:mm:ss tt"), LicenseStartDate = (DateTime)LicenseStartDate, LicenseStartDateStr = ((DateTime)LicenseStartDate).ToString("MM/dd/yyyy hh:mm:ss tt"), LicensePurchaseId = LicensePurchaseId }; else return null; }
public void UpdateSortedProducts(IOrderedQueryable<Product> sortedProducts) { _products = sortedProducts.ToList(); }
/// <summary> /// Another level of ordering by a property /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="descending">if set to <c>true</c> [descending].</param> /// <returns>IOrderedQueryable<T>.</returns> public static IOrderedQueryable <T> ThenBy <T>(this IOrderedQueryable <T> source, string propertyName, bool descending = false) { return(OrderingHelper(source, propertyName, descending, true)); }