/// <summary> /// Create a new OrderByQueryToken given the expression and direction /// </summary> /// <param name="expression">The expression according to which to order the results.</param> /// <param name="direction">The direction of the ordering.</param> public OrderByQueryToken(QueryToken expression, OrderByDirection direction) { ExceptionUtils.CheckArgumentNotNull(expression, "expression"); this.expression = expression; this.direction = direction; }
/// <summary> /// Creates a new filter instance with the given property and order by direction /// </summary> /// <param name="propertyName">The name of the Content property to sort on</param> /// <param name="direction">The direction in which to sort the results</param> /// <exception cref="ArgumentException">Thrown if the provided propertyName is invalid</exception> public OrderBySearchFilter(string propertyName, OrderByDirection direction) { if (string.IsNullOrEmpty(propertyName)) throw new ArgumentException("Property Name must be specified"); Field = "order"; Comparison = direction == OrderByDirection.Ascending ? "=" : "=-"; Value = propertyName; }
public static IQueryable OrderByProperty(IQueryable query, IEdmModel model, IEdmProperty property, OrderByDirection direction, Type type, bool alreadyOrdered = false) { // property aliasing string propertyName = EdmLibHelpers.GetClrPropertyName(property, model); LambdaExpression orderByLambda = GetPropertyAccessLambda(type, propertyName); return OrderBy(query, orderByLambda, direction, type, alreadyOrdered); }
public OrderBy(IProjection projection, OrderByDirection direction) { Require.NotNull(projection, "projection"); Direction = direction; Projection = projection; }
/// <summary> /// Initializes a new instance of the <see cref="OrderByPropertyNode"/> class. /// </summary> /// <param name="property">The <see cref="IEdmProperty"/> for this node.</param> /// <param name="direction">The <see cref="OrderByDirection"/> for this node.</param> public OrderByPropertyNode(IEdmProperty property, OrderByDirection direction) : base(direction) { if (property == null) { throw Error.ArgumentNull("property"); } Property = property; }
/// <summary> /// Creates an <see cref="OrderByClause"/>. /// </summary> /// <param name="thenBy">The next orderby to perform after performing this orderby, can be null in the case of only a single orderby expression.</param> /// <param name="expression">The order-by expression. Cannot be null.</param> /// <param name="direction">The direction to order.</param> /// <param name="rangeVariable">The rangeVariable for the expression which represents a single value from the collection we iterate over. </param> /// <exception cref="System.ArgumentNullException">Throws if the input expression or rangeVariable is null.</exception> public OrderByClause(OrderByClause thenBy, SingleValueNode expression, OrderByDirection direction, RangeVariable rangeVariable) { ExceptionUtils.CheckArgumentNotNull(expression, "expression"); ExceptionUtils.CheckArgumentNotNull(rangeVariable, "parameter"); this.thenBy = thenBy; this.expression = expression; this.direction = direction; this.rangeVariable = rangeVariable; }
public void Apply_DadoFiltroComOrderSorts_DeveRetornar(Restful.Query.Filter.Filters.Ordering.OrderByDirection sorts, OrderByDirection expected) { _filterStub .Setup(p => p.OrderBy) .Returns(new Restful.Query.Filter.Filters.Ordering.OrderBy(new List<Restful.Query.Filter.Filters.Ordering.Field> { new Restful.Query.Filter.Filters.Ordering.Field("", sorts) })); var orderDirection = new OrderDirection(); var actual = orderDirection.Apply(_filterStub.Object); actual.Should().Be(expected); }
public OrderByClause AddPart(string columnName, OrderByDirection direction = OrderByDirection.Default) { columnName = SqlSanitizer.SanitizeObjectName(columnName); switch (direction) { case OrderByDirection.Asc: columnName += " ASC"; break; case OrderByDirection.Desc: columnName += " DESC"; break; } parts.Add(columnName); return this; }
private static IQueryable OrderBy(IQueryable query, LambdaExpression orderByLambda, OrderByDirection direction, Type type, bool alreadyOrdered = false) { Type returnType = orderByLambda.Body.Type; MethodInfo orderByMethod = null; IOrderedQueryable orderedQuery = null; // unfortunately unordered L2O.AsQueryable implements IOrderedQueryable // so we can't try casting to IOrderedQueryable to provide a clue to whether // we should be calling ThenBy or ThenByDescending if (alreadyOrdered) { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.QueryableThenByGeneric.MakeGenericMethod(type, returnType); } else { orderByMethod = ExpressionHelperMethods.QueryableThenByDescendingGeneric.MakeGenericMethod(type, returnType); } orderedQuery = query as IOrderedQueryable; orderedQuery = orderByMethod.Invoke(null, new object[] { orderedQuery, orderByLambda }) as IOrderedQueryable; } else { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.QueryableOrderByGeneric.MakeGenericMethod(type, returnType); } else { orderByMethod = ExpressionHelperMethods.QueryableOrderByDescendingGeneric.MakeGenericMethod(type, returnType); } orderedQuery = orderByMethod.Invoke(null, new object[] { query, orderByLambda }) as IOrderedQueryable; } return orderedQuery; }
/// <summary> /// Instantiates a new instance of <see cref="OrderByItNode"/> class. /// </summary> /// <param name="direction">The <see cref="OrderByDirection"/> for this node.</param> public OrderByItNode(OrderByDirection direction) : base(direction) { }
private Expression BindOrderBy(Expression source, LambdaExpression orderSelector, OrderByDirection orderType) { List<OrderByExpression> myThenBys = _thenBys; _thenBys = null; ProjectionExpression projection = VisitSequence(source); _map[orderSelector.Parameters[0]] = projection.Projector; var orderings = new List<OrderByExpression>(); orderings.Add(new OrderByExpression(orderSelector.Body, orderType)); if (myThenBys != null) { for (Int32 i = myThenBys.Count - 1; i >= 0; i--) { OrderByExpression tb = myThenBys[i]; var lambda = (LambdaExpression) tb.Expression; _map[lambda.Parameters[0]] = projection.Projector; orderings.Add(new OrderByExpression(Visit(lambda.Body), tb.Direction)); } } SourceAlias alias = GetNextAlias(); ProjectedColumns pc = ProjectColumns(projection.Projector, alias, projection.Source.Alias); return new ProjectionExpression( new SelectExpression(alias, pc.Columns, projection.Source, null, orderings.AsReadOnly(), null), pc.Projector ); }
/// <summary> /// Initializes an instance of <see cref="OrderByNode"/> /// </summary> /// <param name="expression">The order-by expression.</param> /// <param name="direction">The direction to order.</param> public OrderByNode(QueryNode expression, OrderByDirection direction) { this.Expression = expression; this.Direction = direction; }
public PagedResult <OrderSummary> GetOrderSummary(int corpClientId, string customer, DateTimeOffset?createdOnFrom, DateTimeOffset?createdOnTo, DateTimeOffset?paidOnFrom, DateTimeOffset?paidOnTo, DateTime?completeByFrom, DateTime?completeByTo, List <int> paymentStatus, List <int> orderStatus, OrderSummaryOrderBy orderBy, OrderByDirection direction, int?page, int?pageSize) { var sqlParams = new List <SqlParameter> { new SqlParameter("@corpClientId", corpClientId) }; var query = new StringBuilder(@"Select * FROM (SELECT C.CorpClientId, O.OrderId, O.OrderNumber, CASE C.CustomerTypeId WHEN 1 THEN RTRIM(c.Name + ' ' + ISNULL(c.LastName,'')) ELSE c.DBAName END AS Name, CASE C.CustomerTypeId WHEN 1 THEN c.CPF ELSE c.CNPJ END AS SocialIdentifier, P.PaymentStatusId, OS.OrderStatusId, C.CustomerTypeId, C.CustomerId, P.Description AS PaymentStatus, OS.Description AS OrderStatus, O.CompleteBy CompleteBy, O.CreatedOn CreatedOn, O.PaidOn PaidOn, ISNULL((SELECT SUM(OI.PriceAfterDiscount) FROM OrderItem OI WHERE OI.OrderId = O.OrderId AND OI.OrderItemStatusId NOT IN (3)),0) AS FinalPrice FROM Customer C JOIN [Order] O ON C.CustomerId = O.CustomerId JOIN PaymentStatus P ON O.PaymentStatusId = P.PaymentStatusId JOIN OrderStatus OS ON O.OrderStatusId = OS.OrderStatusId ) X WHERE CorpClientId = @corpClientId "); if (!string.IsNullOrEmpty(customer)) { query.Append(" AND Name LIKE '%'+ @customer +'%'"); sqlParams.Add(new SqlParameter("@customer", customer) { SqlDbType = SqlDbType.VarChar, Size = 500 }); } if (createdOnFrom.HasValue) { query.Append(" AND CAST(CreatedOn AS DATE) >= @createdOnFrom"); sqlParams.Add(new SqlParameter("@createdOnFrom", createdOnFrom.Value.ToUniversalTime().Date) { SqlDbType = SqlDbType.Date }); } if (createdOnTo.HasValue) { query.Append(" AND CAST(CreatedOn AS DATE) <= @createdOnTo"); sqlParams.Add(new SqlParameter("@createdOnTo", createdOnTo.Value.ToUniversalTime().Date) { SqlDbType = SqlDbType.Date }); } if (paidOnFrom.HasValue) { query.Append(" AND CAST(PaidOn AS DATE) >= @paidOnFrom"); sqlParams.Add(new SqlParameter("@paidOnFrom", paidOnFrom.Value.ToUniversalTime().Date) { SqlDbType = SqlDbType.Date }); } if (paidOnTo.HasValue) { query.Append(" AND CAST(PaidOn AS DATE) <= @paidOnTo"); sqlParams.Add(new SqlParameter("@paidOnTo", paidOnTo.Value.ToUniversalTime().Date) { SqlDbType = SqlDbType.Date }); } if (completeByFrom.HasValue) { query.Append(" AND CompleteBy >= @completeByFrom"); sqlParams.Add(new SqlParameter("@completeByFrom", completeByFrom) { SqlDbType = SqlDbType.Date }); } if (completeByTo.HasValue) { query.Append(" AND CompleteBy <= @completeByTo"); sqlParams.Add(new SqlParameter("@completeByTo", completeByTo) { SqlDbType = SqlDbType.Date }); } if (paymentStatus != null && paymentStatus.Any()) { query.Append($" AND paymentStatusId IN ({string.Join(',', paymentStatus.ToArray())})"); } if (orderStatus != null && orderStatus.Any()) { query.Append($" AND orderStatusId IN ({string.Join(',', orderStatus.ToArray())})"); } var count = context.OrderSummaries.FromSqlRaw(query.ToString(), sqlParams.ToArray()).Count(); if (orderBy == OrderSummaryOrderBy.OrderStatus) { query.Append($" ORDER BY {orderBy} {direction}, CompleteBy"); } else if (orderBy == OrderSummaryOrderBy.CompleteBy) { query.Append($" ORDER BY {orderBy} {direction}, OrderStatus"); } else { query.Append($" ORDER BY {orderBy} {direction},CompleteBy, OrderStatus"); } if (page.HasValue && pageSize.HasValue) { query.Append($" OFFSET {(page > 0 ? page - 1 : 0) * pageSize} ROWS FETCH NEXT {pageSize} ROWS ONLY"); } var data = context.OrderSummaries.FromSqlRaw(query.ToString(), sqlParams.ToArray()).ToList(); var result = mapper.Map <IEnumerable <OrderSummary> >(data); return(new PagedResult <OrderSummary> { CurrentPage = page ?? 1, Data = result, RecordCount = count, RecordsPerpage = pageSize ?? count }); }
public OrderByClause(ObjectReference reference, OrderByDirection direction) { _reference = reference; _direction = direction; }
public async Task <IEnumerable <RawMaterial> > GetAll(int corpClientId, OrderByDirection direction) { return(await rawMaterialRepository.GetAll(corpClientId, direction)); }
public IOrderBy <TClass> By(string propertyName, OrderByDirection direction) { _elements.Add(new OrderByElement <TClass>(propertyName, direction)); return(this); }
private IOrderedQueryable ApplyToCore(IQueryable query, ODataQuerySettings querySettings) { if (Context.ElementClrType == null) { throw Error.NotSupported(SRResources.ApplyToOnUntypedQueryOption, "ApplyTo"); } ICollection <OrderByNode> nodes = OrderByNodes; bool alreadyOrdered = false; IQueryable querySoFar = query; HashSet <object> propertiesSoFar = new HashSet <object>(); HashSet <string> openPropertiesSoFar = new HashSet <string>(); bool orderByItSeen = false; foreach (OrderByNode node in nodes) { OrderByPropertyNode propertyNode = node as OrderByPropertyNode; OrderByOpenPropertyNode openPropertyNode = node as OrderByOpenPropertyNode; OrderByCountNode countNode = node as OrderByCountNode; if (propertyNode != null) { // Use autonomy class to achieve value equality for HasSet. var edmPropertyWithPath = new { propertyNode.Property, propertyNode.PropertyPath }; OrderByDirection direction = propertyNode.Direction; // This check prevents queries with duplicate properties (e.g. $orderby=Id,Id,Id,Id...) from causing stack overflows if (propertiesSoFar.Contains(edmPropertyWithPath)) { throw new ODataException(Error.Format(SRResources.OrderByDuplicateProperty, edmPropertyWithPath.PropertyPath)); } propertiesSoFar.Add(edmPropertyWithPath); if (propertyNode.OrderByClause != null) { querySoFar = AddOrderByQueryForProperty(query, querySettings, propertyNode.OrderByClause, querySoFar, direction, alreadyOrdered); } else { querySoFar = ExpressionHelpers.OrderByProperty(querySoFar, Context.Model, edmPropertyWithPath.Property, direction, Context.ElementClrType, alreadyOrdered); } alreadyOrdered = true; } else if (openPropertyNode != null) { // This check prevents queries with duplicate properties (e.g. $orderby=Id,Id,Id,Id...) from causing stack overflows if (openPropertiesSoFar.Contains(openPropertyNode.PropertyName)) { throw new ODataException(Error.Format(SRResources.OrderByDuplicateProperty, openPropertyNode.PropertyPath)); } openPropertiesSoFar.Add(openPropertyNode.PropertyName); Contract.Assert(openPropertyNode.OrderByClause != null); querySoFar = AddOrderByQueryForProperty(query, querySettings, openPropertyNode.OrderByClause, querySoFar, openPropertyNode.Direction, alreadyOrdered); alreadyOrdered = true; } else if (countNode != null) { Contract.Assert(countNode.OrderByClause != null); querySoFar = AddOrderByQueryForProperty(query, querySettings, countNode.OrderByClause, querySoFar, countNode.Direction, alreadyOrdered); alreadyOrdered = true; } else { // This check prevents queries with duplicate nodes (e.g. $orderby=$it,$it,$it,$it...) from causing stack overflows if (orderByItSeen) { throw new ODataException(Error.Format(SRResources.OrderByDuplicateIt)); } querySoFar = ExpressionHelpers.OrderByIt(querySoFar, node.Direction, Context.ElementClrType, alreadyOrdered); alreadyOrdered = true; orderByItSeen = true; } } return(querySoFar as IOrderedQueryable); }
public async Task <RepositoryResponse <PaginationModel <InfoArticleViewModel> > > Get(int?pageSize = 15, int?pageIndex = 0, string orderBy = "Id", OrderByDirection direction = OrderByDirection.Ascending) { var data = await InfoArticleViewModel.Repository.GetModelListByAsync( m => m.Status != (int)SWStatus.Deleted && m.Specificulture == _lang, orderBy, direction, pageSize, pageIndex).ConfigureAwait(false); if (data.IsSucceed) { data.Data.Items.ForEach(a => a.DetailsUrl = SwCmsHelper.GetRouterUrl("Article", new { a.SeoName }, Request, Url)); } return(data); }
protected virtual int?GetSequence(Playlist playlist, int sequence, QueryOperator @operator, OrderByDirection direction) { using (var database = this.DatabaseFactory.Create()) { using (var transaction = database.BeginTransaction(database.PreferredIsolationLevel)) { var query = this.SequenceQueries.GetOrAdd( new Tuple <QueryOperator, OrderByDirection>(@operator, direction), key => { var table = database.Tables.PlaylistItem; var column = table.GetColumn(ColumnConfig.By("Sequence")); var builder = database.QueryFactory.Build(); builder.Output.AddColumn(column); builder.Source.AddTable(table); builder.Filter.AddColumn(table.GetColumn(ColumnConfig.By("Playlist_Id"))); builder.Filter.AddColumn(column).Operator = builder.Filter.CreateOperator(@operator); builder.Sort.AddColumn(column).Direction = direction; return(builder.Build()); } ); return(database.ExecuteScalar <int?>(query, (parameters, phase) => { switch (phase) { case DatabaseParameterPhase.Fetch: parameters["playlistId"] = playlist.Id; parameters["sequence"] = sequence; break; } }, transaction)); } } }
public virtual string GetOrderByWord(OrderByDirection orderByDirection) { return(orderByDirection == OrderByDirection.Descending ? "DESC" : ""); }
/// <summary> /// Merges two or more sequences that are in a common order (either ascending or descending) into /// a single sequence that preserves that order. /// </summary> /// <typeparam name="TSource">The type of the elements in the sequence</typeparam> /// <param name="source">The primary sequence with which to merge</param> /// <param name="direction">The ordering that all sequences must already exhibit</param> /// <param name="comparer">The comparer used to evaluate the relative order between elements</param> /// <param name="otherSequences">A variable argument array of zero or more other sequences to merge with</param> /// <returns>A merged, order-preserving sequence containing al of the elements of the original sequences</returns> public static IEnumerable <TSource> SortedMerge <TSource>(this IEnumerable <TSource> source, OrderByDirection direction, IComparer <TSource> comparer, params IEnumerable <TSource>[] otherSequences) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (otherSequences == null) { throw new ArgumentNullException(nameof(otherSequences)); } if (otherSequences.Length == 0) { return(source); // optimization for when otherSequences is empty } comparer = comparer ?? Comparer <TSource> .Default; // define an precedence function based on the comparer and direction // this is a function that will return True if (b) should precede (a) var precedenceFunc = direction == OrderByDirection.Ascending ? (Func <TSource, TSource, bool>)((a, b) => comparer.Compare(b, a) < 0) : (a, b) => comparer.Compare(b, a) > 0; // return the sorted merge result return(SortedMergeImpl(precedenceFunc, new[] { source }.Concat(otherSequences))); }
/// <summary> /// Merges two or more sequences that are in a common order (either ascending or descending) into /// a single sequence that preserves that order. /// </summary> /// <remarks> /// Using SortedMerge on sequences that are not ordered or are not in the same order produces /// undefined results.<br/> /// <c>SortedMerge</c> uses performs the merge in a deferred, streaming manner. <br/> /// /// Here is an example of a merge, as well as the produced result: /// <code> /// var s1 = new[] { 3, 7, 11 }; /// var s2 = new[] { 2, 4, 20 }; /// var s3 = new[] { 17, 19, 25 }; /// var merged = s1.SortedMerge( OrderByDirection.Ascending, s2, s3 ); /// var result = merged.ToArray(); /// // result will be: /// // { 2, 3, 4, 7, 11, 17, 19, 20, 25 } /// </code> /// </remarks> /// <typeparam name="TSource">The type of the elements of the sequence</typeparam> /// <param name="source">The primary sequence with which to merge</param> /// <param name="direction">The ordering that all sequences must already exhibit</param> /// <param name="otherSequences">A variable argument array of zero or more other sequences to merge with</param> /// <returns>A merged, order-preserving sequence containing all of the elements of the original sequences</returns> public static IEnumerable <TSource> SortedMerge <TSource>(this IEnumerable <TSource> source, OrderByDirection direction, params IEnumerable <TSource>[] otherSequences) { return(SortedMerge(source, direction, null, otherSequences)); }
public OrderByExpression(string fieldName, OrderByDirection direction) { this.FieldName = fieldName; this.Direction = direction; }
private IQueryable AddOrderByQueryForProperty(IQueryable query, ODataQuerySettings querySettings, OrderByClause orderbyClause, IQueryable querySoFar, OrderByDirection direction, bool alreadyOrdered) { ODataQuerySettings updatedSettings = Context.UpdateQuerySettings(querySettings, query); LambdaExpression orderByExpression = FilterBinder.Bind(query, orderbyClause, Context.ElementClrType, Context, updatedSettings); querySoFar = ExpressionHelpers.OrderBy(querySoFar, orderByExpression, direction, Context.ElementClrType, alreadyOrdered); return(querySoFar); }
/// <summary> /// Combines <see cref="OrderBy{T, TKey}(IEnumerable{T}, Func{T, TKey}, IComparer{TKey}, OrderByDirection)"/>, /// where each element is its key, and <see cref="Enumerable.Take{TSource}"/> /// in a single operation. /// An additional parameter specifies the direction of the sort /// </summary> /// <typeparam name="T">Type of elements in the sequence.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="count">Number of (maximum) elements to return.</param> /// <param name="direction">The direction in which to sort the elements</param> /// <returns>A sequence containing at most top <paramref name="count"/> /// elements from source, in the specified order.</returns> /// <remarks> /// This operator uses deferred execution and streams it results. /// </remarks> public static IEnumerable <T> PartialSort <T>(this IEnumerable <T> source, int count, OrderByDirection direction) { return(source.PartialSort(count, null, direction)); }
protected void WriteOrderByDirection(OrderByDirection direction) { switch (direction) { case OrderByDirection.Descending: Write(" desc"); break; default: Write(" asc"); break; } }
public static IQueryable OrderByProperty(IQueryable query, IEdmModel model, IEdmProperty property, OrderByDirection direction, Type type, bool alreadyOrdered = false) { // property aliasing string propertyName = EdmLibHelpers.GetClrPropertyName(property, model); LambdaExpression orderByLambda = GetPropertyAccessLambda(type, propertyName); return(OrderBy(query, orderByLambda, direction, type, alreadyOrdered)); }
public static IQueryable OrderByIt(IQueryable query, OrderByDirection direction, Type type, bool alreadyOrdered = false) { ParameterExpression odataItParameter = Expression.Parameter(type, "$it"); LambdaExpression orderByLambda = Expression.Lambda(odataItParameter, odataItParameter); return OrderBy(query, orderByLambda, direction, type, alreadyOrdered); }
public static IQueryable OrderBy(IQueryable query, LambdaExpression orderByLambda, OrderByDirection direction, Type type, bool alreadyOrdered = false) { Type returnType = orderByLambda.Body.Type; MethodInfo orderByMethod = null; IOrderedQueryable orderedQuery = null; // unfortunately unordered L2O.AsQueryable implements IOrderedQueryable // so we can't try casting to IOrderedQueryable to provide a clue to whether // we should be calling ThenBy or ThenByDescending if (alreadyOrdered) { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.QueryableThenByGeneric.MakeGenericMethod(type, returnType); } else { orderByMethod = ExpressionHelperMethods.QueryableThenByDescendingGeneric.MakeGenericMethod(type, returnType); } orderedQuery = query as IOrderedQueryable; orderedQuery = orderByMethod.Invoke(null, new object[] { orderedQuery, orderByLambda }) as IOrderedQueryable; } else { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.QueryableOrderByGeneric.MakeGenericMethod(type, returnType); } else { orderByMethod = ExpressionHelperMethods.QueryableOrderByDescendingGeneric.MakeGenericMethod(type, returnType); } orderedQuery = orderByMethod.Invoke(null, new object[] { query, orderByLambda }) as IOrderedQueryable; } return(orderedQuery); }
public virtual string GetOrderByWord(OrderByDirection orderByDirection) { return orderByDirection == OrderByDirection.Descending ? "DESC" : ""; }
public static Expression OrderBy( Expression source, LambdaExpression orderByLambda, Type elementType, OrderByDirection direction, bool alreadyOrdered = false) { Type returnType = orderByLambda.Body.Type; MethodInfo orderByMethod; if (!alreadyOrdered) { if (typeof(IQueryable).IsAssignableFrom(source.Type)) { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.QueryableOrderByGeneric.MakeGenericMethod(elementType, returnType); } else { orderByMethod = ExpressionHelperMethods.QueryableOrderByDescendingGeneric.MakeGenericMethod(elementType, returnType); } } else { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.EnumerableOrderByGeneric.MakeGenericMethod(elementType, returnType); } else { orderByMethod = ExpressionHelperMethods.EnumerableOrderByDescendingGeneric.MakeGenericMethod(elementType, returnType); } } } else { if (typeof(IQueryable).IsAssignableFrom(source.Type)) { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.QueryableThenByGeneric.MakeGenericMethod(elementType, returnType); } else { orderByMethod = ExpressionHelperMethods.QueryableThenByDescendingGeneric.MakeGenericMethod(elementType, returnType); } } else { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.EnumerableThenByGeneric.MakeGenericMethod(elementType, returnType); } else { orderByMethod = ExpressionHelperMethods.EnumerableThenByDescendingGeneric.MakeGenericMethod(elementType, returnType); } } } return(Expression.Call(null, orderByMethod, new[] { source, orderByLambda })); }
/// <summary> /// Merges two or more sequences that are in a common order (either ascending or descending) into /// a single sequence that preserves that order. /// </summary> /// <typeparam name="TSource">The type of the elements in the sequence</typeparam> /// <param name="source">The primary sequence with which to merge</param> /// <param name="direction">The ordering that all sequences must already exhibit</param> /// <param name="comparer">The comparer used to evaluate the relative order between elements</param> /// <param name="otherSequences">A variable argument array of zero or more other sequences to merge with</param> /// <returns>A merged, order-preserving sequence containing al of the elements of the original sequences</returns> public static IEnumerable <TSource> SortedMerge <TSource>(this IEnumerable <TSource> source, OrderByDirection direction, IComparer <TSource> comparer, params IEnumerable <TSource>[] otherSequences) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (otherSequences == null) { throw new ArgumentNullException(nameof(otherSequences)); } if (otherSequences.Length == 0) { return(source); // optimization for when otherSequences is empty } comparer = comparer ?? Comparer <TSource> .Default; // define an precedence function based on the comparer and direction // this is a function that will return True if (b) should precede (a) var precedenceFunc = direction == OrderByDirection.Ascending ? (Func <TSource, TSource, bool>)((a, b) => comparer.Compare(b, a) < 0) : (a, b) => comparer.Compare(b, a) > 0; // return the sorted merge result return(Impl(new[] { source }.Concat(otherSequences))); // Private implementation method that performs a merge of multiple, ordered sequences using // a precedence function which encodes order-sensitive comparison logic based on the caller's arguments. // // The algorithm employed in this implementation is not necessarily the most optimal way to merge // two sequences. A swap-compare version would probably be somewhat more efficient - but at the // expense of considerably more complexity. One possible optimization would be to detect that only // a single sequence remains (all other being consumed) and break out of the main while-loop and // simply yield the items that are part of the final sequence. // // The algorithm used here will perform N*(K1+K2+...Kn-1) comparisons, where <c>N => otherSequences.Count()+1.</c> IEnumerable <TSource> Impl(IEnumerable <IEnumerable <TSource> > sequences) { using (var disposables = new DisposableGroup <TSource>(sequences.Select(e => e.GetEnumerator()).Acquire())) { var iterators = disposables.Iterators; // prime all of the iterators by advancing them to their first element (if any) // NOTE: We start with the last index to simplify the removal of an iterator if // it happens to be terminal (no items) before we start merging for (var i = iterators.Count - 1; i >= 0; i--) { if (!iterators[i].MoveNext()) { disposables.Exclude(i); } } // while all iterators have not yet been consumed... while (iterators.Count > 0) { var nextIndex = 0; var nextValue = disposables[0].Current; // find the next least element to return for (var i = 1; i < iterators.Count; i++) { var anotherElement = disposables[i].Current; // determine which element follows based on ordering function if (precedenceFunc(nextValue, anotherElement)) { nextIndex = i; nextValue = anotherElement; } } yield return(nextValue); // next value in precedence order // advance iterator that yielded element, excluding it when consumed if (!iterators[nextIndex].MoveNext()) { disposables.Exclude(nextIndex); } } } } }
/// <summary> /// Initializes a new instance of the <see cref="OrderByNode"/> class. /// </summary> /// <param name="direction">The direction of the sort order.</param> protected OrderByNode(OrderByDirection direction) { Direction = direction; PropertyPath = String.Empty; }
public PagedResult <OrderItemReport> GetOrderItemReport(int corpClientId, int?orderNumber, List <long> productIds, int massUnitId, int volumeUnitId, List <OrderStatusEnum> orderStatus, List <OrderItemStatusEnum> itemStatus, DateTime?completeByFrom, DateTime?completeByTo, string customer, long?customerId, OrderItemReportOrderBy orderBy, OrderByDirection direction, int?page, int?pageSize) { var sqlParams = new List <SqlParameter> { new SqlParameter("@corpClientId", corpClientId), new SqlParameter("@mid", massUnitId), new SqlParameter("@vid", volumeUnitId) }; var query = new StringBuilder(@"SELECT * FROM(SELECT O.OrderId, I.OrderItemId, O.OrderNumber, C.customerTypeId, OS.OrderStatusId AS OrderStatusId, OS.Description AS OrderStatus, CASE C.CustomerTypeId WHEN 1 THEN RTRIM(c.Name + ' ' + ISNULL(c.LastName,'')) ELSE c.DBAName END AS Customer, CASE C.CustomerTypeId WHEN 1 THEN c.CPF ELSE c.CNPJ END AS SocialIdentifier, I.ItemNumber, P.Name as Product, OIS.Description as OrderItemStatus, OIS.OrderItemStatusId as OrderItemStatusId, I.PriceAfterDiscount as FinalPrice, I.LastStatusDate, O.CompleteBy, P.ProductId, C.CustomerId, CASE WHEN M.MeasureUnitTypeId = 1 THEN CAST(dbo.ConvertMeasure(M.MeasureUnitId,I.Quantity,@mid) as decimal(18,2)) ELSE CAST(dbo.ConvertMeasure(M.MeasureUnitId,I.Quantity,@vid) as decimal(18,2)) END as Quantity, (SELECT M2.ShortName FROM MeasureUnit M2 WHERE M2.MeasureUnitId = IIF(M.MeasureUnitTypeId=1,@mid,@vid)) as MeasureUnit FROM [Order] O JOIN OrderStatus OS ON O.OrderStatusId = OS.OrderStatusId JOIN PaymentStatus PS ON O.PaymentStatusId = PS.PaymentStatusId JOIN OrderItem I ON O.OrderId = I.OrderId JOIN Customer C ON C.CustomerId = O.CustomerId JOIN OrderItemStatus OIS ON I.OrderItemStatusId = OIS.OrderItemStatusId JOIN MeasureUnit M ON I.MeasureUnitId = M.MeasureUnitId JOIN Product P ON I.ProductId = P.ProductId WHERE P.CorpClientId = @corpClientId AND C.CorpClientId = @corpClientId) X WHERE 1 = 1 "); if (productIds != null && productIds.Any()) { query.Append($" AND ProductId IN ({string.Join(',', productIds.Select(i => i).ToArray())})"); } if (customerId.HasValue) { query.Append($" AND CustomerId = @customerId"); sqlParams.Add(new SqlParameter("@customerId", customerId) { SqlDbType = SqlDbType.BigInt }); } if (completeByFrom.HasValue) { query.Append(" AND CompleteBy >= @completeByFrom"); sqlParams.Add(new SqlParameter("@completeByFrom", completeByFrom) { SqlDbType = SqlDbType.Date }); } if (completeByTo.HasValue) { query.Append(" AND CompleteBy <= @completeByTo"); sqlParams.Add(new SqlParameter("@completeByTo", completeByTo) { SqlDbType = SqlDbType.Date }); } if (!string.IsNullOrEmpty(customer)) { query.Append(" AND Customer LIKE '%'+ @customer +'%'"); sqlParams.Add(new SqlParameter("@customer", customer) { SqlDbType = SqlDbType.VarChar, Size = 500 }); } if (itemStatus != null && itemStatus.Any()) { query.Append($" AND OrderItemStatusId IN ({string.Join(',', itemStatus.Select(i => (int)i).ToArray())})"); } if (orderNumber.HasValue) { query.Append($" AND OrderNumber = @OrderNumber"); sqlParams.Add(new SqlParameter("@OrderNumber", orderNumber.Value) { SqlDbType = SqlDbType.Int }); } if (orderStatus != null && orderStatus.Any()) { query.Append($" AND orderStatusId IN ({string.Join(',', orderStatus.Select(i => (int)i).ToArray())})"); } var count = context.OrderItemReports.FromSqlRaw(query.ToString(), sqlParams.ToArray()).Count(); if (orderBy == OrderItemReportOrderBy.OrderItemStatus) { query.Append($" ORDER BY {orderBy} {direction}, Product ASC"); } else if (orderBy == OrderItemReportOrderBy.Product) { query.Append($" ORDER BY {orderBy} {direction}, OrderItemStatus ASC"); } else { query.Append($" ORDER BY {orderBy} {direction}, OrderItemStatus ASC, Product ASC"); } if (page.HasValue && pageSize.HasValue) { query.Append($" OFFSET {(page > 0 ? page - 1 : 0) * pageSize} ROWS FETCH NEXT {pageSize} ROWS ONLY"); } var data = context.OrderItemReports.FromSqlRaw(query.ToString(), sqlParams.ToArray()).ToList(); var result = mapper.Map <IEnumerable <OrderItemReport> >(data); return(new PagedResult <OrderItemReport> { CurrentPage = page ?? 1, Data = result, RecordCount = count, RecordsPerpage = pageSize ?? count }); }
/// <summary> /// Creates an ORDER BY term /// </summary> public OrderByTerm() { field = null; table = null; direction = OrderByDirection.Ascending; }
private Expression BindThenBy(Expression source, LambdaExpression orderSelector, OrderByDirection orderType) { if (_thenBys == null) { _thenBys = new List<OrderByExpression>(); } _thenBys.Add(new OrderByExpression(orderSelector, orderType)); return Visit(source); }
public OrderByTerm(Enum field, FromTerm table, OrderByDirection dir) : this(field.ToString(), table, dir) {}
// constructors /// <summary> /// Initializes an member of the OrderByExpression class. /// </summary> /// <param name="key">An expression identifying the key of the order by clause.</param> /// <param name="direction">The direction of the order by clause.</param> internal OrderByExpression(Expression key, OrderByDirection direction) { Expression = key; Direction = direction; }
// constructors /// <summary> /// Initializes an instance of the OrderByClause class. /// </summary> /// <param name="key">An expression identifying the key of the order by clause.</param> /// <param name="direction">The direction of the order by clause.</param> public OrderByClause(LambdaExpression key, OrderByDirection direction) { _key = key; _direction = direction; }
/// <summary> /// Performs a subsequent ordering of the elements in a sequence in the specified order by using a specified comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam> /// <param name="value">An IOrderedEnumerable<TElement> that contains elements to sort.</param> /// <param name="keySelector">A function to extract a key from each element.</param> /// <param name="comparer">An IComparer<T> to compare keys.</param> /// <param name="direction">Ascending or Descending</param> /// <returns>An IOrderedEnumerable<TElement> whose elements are sorted according to a key.</returns> public static IOrderedEnumerable <TSource> ThenByWithDirection <TSource, TKey>(this IOrderedEnumerable <TSource> value, Func <TSource, TKey> keySelector, IComparer <TKey> comparer, OrderByDirection direction) { // Ideally, if order is not needed, the method would not be called, but sometimes it's easier to code a "no sort" option. // Testing shows the "OrderByDirection.None" is negligible on large IOrderedEnumerables if (direction == OrderByDirection.None) { return(value); } return(direction == OrderByDirection.Descending ? value.ThenByDescending(keySelector, comparer) : value.ThenBy(keySelector, comparer)); }
public PagedResult <SummarizedOrderReport> GetSummarizedReport(int corpClientId, int volumeUnitId, int massUnitId, List <OrderItemStatusEnum> itemStatus, List <long> productIds, SummarizedOrderOrderBy orderBy, OrderByDirection direction, int?page, int?pageSize) { var sqlParams = new List <SqlParameter> { new SqlParameter("@corpClientId", corpClientId), new SqlParameter("@mid", massUnitId), new SqlParameter("@vid", volumeUnitId) }; var query = new StringBuilder(@"SELECT * FROM(SELECT NEWID() as RowId, ProductId, Product, OrderItemStatusId, OrderItemStatus, MeasureUnitTypeId, SUM(Quantity) as Quantity, CASE WHEN MeasureUnitTypeId = 1 THEN @mid ELSE @vid END as MeasureUnitId, (SELECT M.Description FROM MeasureUnit M WHERE M.MeasureUnitId = IIF(X.MeasureUnitTypeId=1,@mid,@vid)) as MeasureUnit, (SELECT M.ShortName FROM MeasureUnit M WHERE M.MeasureUnitId = IIF(X.MeasureUnitTypeId=1,@mid,@vid)) as ShortMeasureUnit FROM (SELECT P.ProductId, P.Name as Product, CASE WHEN U.MeasureUnitTypeId = 1 THEN CAST(dbo.ConvertMeasure(I.MeasureUnitId,I.Quantity,@mid) as decimal(18,2)) ELSE CAST(dbo.ConvertMeasure(I.MeasureUnitId,I.Quantity,@vid) as decimal(18,2)) END as Quantity, CASE WHEN U.MeasureUnitTypeId = 1 THEN 1 ELSE 5 END as MeasureUnitId, U.MeasureUnitTypeId, S.OrderItemStatusId, S.Description AS OrderItemStatus FROM OrderItem I JOIN Product P ON I.ProductId = P.ProductId JOIN OrderItemStatus S ON I.OrderItemStatusId = S.OrderItemStatusId JOIN MeasureUnit U ON I.MeasureUnitId = U.MeasureUnitId WHERE P.CorpClientId = @corpClientId) X GROUP BY ProductId, Product, MeasureUnitTypeId, OrderItemStatusId, OrderItemStatus, MeasureUnitId ) X WHERE 1 = 1 "); if (itemStatus != null && itemStatus.Any()) { query.Append($" AND OrderItemStatusId IN ({string.Join(',', itemStatus.Select(i => (int)i).ToArray())})"); } if (productIds != null && productIds.Any()) { query.Append($" AND ProductId IN ({string.Join(',', productIds.Select(i => i).ToArray())})"); } var count = context.SummarizedOrderReports.FromSqlRaw(query.ToString(), sqlParams.ToArray()).Count(); if (orderBy == SummarizedOrderOrderBy.OrderItemStatus) { query.Append($" ORDER BY {orderBy} {direction}, Product ASC"); } else if (orderBy == SummarizedOrderOrderBy.Product) { query.Append($" ORDER BY {orderBy} {direction}, OrderItemStatus ASC"); } else { query.Append($" ORDER BY {orderBy} {direction}, OrderItemStatus ASC, Product ASC"); } if (page.HasValue && pageSize.HasValue) { query.Append($" OFFSET {(page > 0 ? page - 1 : 0) * pageSize} ROWS FETCH NEXT {pageSize} ROWS ONLY"); } var data = context.SummarizedOrderReports.FromSqlRaw(query.ToString(), sqlParams.ToArray()).ToList(); var result = mapper.Map <IEnumerable <SummarizedOrderReport> >(data); return(new PagedResult <SummarizedOrderReport> { CurrentPage = page ?? 1, Data = result, RecordCount = count, RecordsPerpage = pageSize ?? count }); }
/// <summary> /// Creates an ORDER BY term with field name and table alias /// </summary> /// <param name="field">Name of a field to order by</param> /// <param name="table">The table this field belongs to</param> /// <param name="dir">Order by direction</param> public OrderByTerm(string field, FromTerm table, OrderByDirection dir) { this.field = field; this.table = table; direction = dir; }
/// <summary> /// Performs a subsequent ordering of the elements in a sequence in the specified order by using the default comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam> /// <param name="value">An IOrderedEnumerable<TElement> that contains elements to sort.</param> /// <param name="keySelector">A function to extract a key from each element.</param> /// <param name="direction">Ascending or Descending</param> /// <returns>An IOrderedEnumerable<TElement> whose elements are sorted according to a key.</returns> public static IOrderedEnumerable <TSource> ThenByWithDirection <TSource, TKey>(this IOrderedEnumerable <TSource> value, Func <TSource, TKey> keySelector, OrderByDirection direction) { return(value.ThenByWithDirection(keySelector, default(IComparer <TKey>), direction)); }
/// <summary> /// Creates an ORDER BY term with field name and no table alias /// </summary> /// <param name="field">Name of a field to order by</param> /// <param name="dir">Order by direction</param> public OrderByTerm(string field, OrderByDirection dir) : this(field, null, dir) {}
public async Task <PagedResult <RawMaterial> > GetPaged(int corpClientId, int page, int pageSize, string name, OrderByDirection direction) { return(await rawMaterialRepository.GetPaged(corpClientId, page, pageSize, name, direction)); }
private async Task <bool> Search() { _searchTokenSource?.Dispose(); _searchTokenSource = new CancellationTokenSource(); return(await Task.Run(async() => { try { SearchResult = null; var db = new DatabaseInteraction(); var types = ObjectTypes.Where((x) => x.Selected).Select((x) => x.Name).ToList(); var searchParams = new DatabaseInteraction.DeepSkyObjectSearchParams(); searchParams.Constellation = SelectedConstellation; searchParams.DsoTypes = types; searchParams.ObjectName = SearchObjectName; searchParams.RightAscension.From = SelectedRAFrom; searchParams.RightAscension.Thru = SelectedRAThrough; searchParams.Declination.From = Nullable.Compare(SelectedDecFrom, SelectedDecThrough) > 0 ? SelectedDecThrough : SelectedDecFrom; searchParams.Declination.Thru = Nullable.Compare(SelectedDecFrom, SelectedDecThrough) > 0 ? SelectedDecFrom : SelectedDecThrough; searchParams.Brightness.From = SelectedBrightnessFrom; searchParams.Brightness.Thru = SelectedBrightnessThrough; searchParams.Magnitude.From = SelectedMagnitudeFrom; searchParams.Magnitude.Thru = SelectedMagnitudeThrough; searchParams.Size.From = SelectedSizeFrom; searchParams.Size.Thru = SelectedSizeThrough; searchParams.SearchOrder.Field = OrderByField.ToString().ToLower(); searchParams.SearchOrder.Direction = OrderByDirection.ToString(); var result = await db.GetDeepSkyObjects( profileService.ActiveProfile.ApplicationSettings.SkyAtlasImageRepository, searchParams, _searchTokenSource.Token ); var longitude = profileService.ActiveProfile.AstrometrySettings.Longitude; var latitude = profileService.ActiveProfile.AstrometrySettings.Latitude; ResetRiseAndSetTimes(); DateTime d = GetReferenceDate(SelectedDate); Parallel.ForEach(result, (obj) => { var cloneDate = d; obj.SetDateAndPosition(cloneDate, latitude, longitude); _searchTokenSource.Token.ThrowIfCancellationRequested(); }); /* Check if Altitude Filter is not default */ if (!(SelectedAltitudeTimeFrom == DateTime.MinValue && SelectedAltitudeTimeThrough == DateTime.MaxValue && SelectedMinimumAltitudeDegrees == 0)) { var filteredList = result.Where((x) => { return x.Altitudes.Where((y) => { return (y.X > DateTimeAxis.ToDouble(SelectedAltitudeTimeFrom) && y.X < DateTimeAxis.ToDouble(SelectedAltitudeTimeThrough)); }).All((z) => { return z.Y > SelectedMinimumAltitudeDegrees; }); }); var count = filteredList.Count(); /* Apply Altitude Filter */ SearchResult = new PagedList <DeepSkyObject>(PageSize, filteredList); } else { SearchResult = new PagedList <DeepSkyObject>(PageSize, result); } } catch (OperationCanceledException) { } return true; })); }
public SimpleOrderByItem(DynamicReference reference, OrderByDirection direction) { _reference = reference; _direction = direction; }
public static IQueryable OrderByProperty(IQueryable query, IEdmProperty property, OrderByDirection direction, Type type, bool alreadyOrdered = false) { LambdaExpression orderByLambda = GetPropertyAccessLambda(type, property.Name); return OrderBy(query, orderByLambda, direction, type, alreadyOrdered); }
/// <summary> /// Combines <see cref="MoreEnumerable.OrderBy{T, TKey}(IEnumerable{T}, Func{T, TKey}, IComparer{TKey}, OrderByDirection)"/>, /// where each element is its key, and <see cref="Enumerable.Take{TSource}"/> /// in a single operation. /// Additional parameters specify how the elements compare to each other and /// the direction of the sort. /// </summary> /// <typeparam name="T">Type of elements in the sequence.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="count">Number of (maximum) elements to return.</param> /// <param name="comparer">A <see cref="IComparer{T}"/> to compare elements.</param> /// <param name="direction">The direction in which to sort the elements</param> /// <returns>A sequence containing at most top <paramref name="count"/> /// elements from source, in the specified order.</returns> /// <remarks> /// This operator uses deferred execution and streams it results. /// </remarks> public static IEnumerable <T> PartialSort <T>(this IEnumerable <T> source, int count, IComparer <T> comparer, OrderByDirection direction) { comparer ??= Comparer <T> .Default; if (direction == OrderByDirection.Descending) { comparer = new ReverseComparer <T>(comparer); } return(source.PartialSort(count, comparer)); }
/// <summary> /// Initializes a new instance of the <see cref="OrderByNode"/> class. /// </summary> /// <param name="direction">The direction of the sort order.</param> protected OrderByNode(OrderByDirection direction) { Direction = direction; }
/// <summary> /// Combines <see cref="MoreEnumerable.OrderBy{T, TKey}(IEnumerable{T}, Func{T, TKey}, OrderByDirection)"/>, /// and <see cref="Enumerable.Take{TSource}"/> in a single operation. /// An additional parameter specifies the direction of the sort /// </summary> /// <typeparam name="TSource">Type of elements in the sequence.</typeparam> /// <typeparam name="TKey">Type of keys.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="keySelector">A function to extract a key from an element.</param> /// <param name="count">Number of (maximum) elements to return.</param> /// <param name="direction">The direction in which to sort the elements</param> /// <returns>A sequence containing at most top <paramref name="count"/> /// elements from source, in the specified order of their keys.</returns> /// <remarks> /// This operator uses deferred execution and streams it results. /// </remarks> public static IEnumerable <TSource> PartialSortBy <TSource, TKey>( this IEnumerable <TSource> source, int count, Func <TSource, TKey> keySelector, OrderByDirection direction) { return(source.PartialSortBy(count, keySelector, null, direction)); }
public static Expression OrderBy( Expression source, LambdaExpression orderByLambda, Type elementType, OrderByDirection direction, bool alreadyOrdered = false) { Type returnType = orderByLambda.Body.Type; MethodInfo orderByMethod; if (!alreadyOrdered) { if (typeof(IQueryable).IsAssignableFrom(source.Type)) { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.QueryableOrderByGeneric.MakeGenericMethod(elementType, returnType); } else { orderByMethod = ExpressionHelperMethods.QueryableOrderByDescendingGeneric.MakeGenericMethod(elementType, returnType); } } else { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.EnumerableOrderByGeneric.MakeGenericMethod(elementType, returnType); } else { orderByMethod = ExpressionHelperMethods.EnumerableOrderByDescendingGeneric.MakeGenericMethod(elementType, returnType); } } } else { if (typeof(IQueryable).IsAssignableFrom(source.Type)) { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.QueryableThenByGeneric.MakeGenericMethod(elementType, returnType); } else { orderByMethod = ExpressionHelperMethods.QueryableThenByDescendingGeneric.MakeGenericMethod(elementType, returnType); } } else { if (direction == OrderByDirection.Ascending) { orderByMethod = ExpressionHelperMethods.EnumerableThenByGeneric.MakeGenericMethod(elementType, returnType); } else { orderByMethod = ExpressionHelperMethods.EnumerableThenByDescendingGeneric.MakeGenericMethod(elementType, returnType); } } } return Expression.Call(null, orderByMethod, new[] { source, orderByLambda }); }
private IOrderedQueryable ApplyToCore(IQueryable query, ODataQuerySettings querySettings) { if (Context.ElementClrType == null) { throw Error.NotSupported(SRResources.ApplyToOnUntypedQueryOption, "ApplyTo"); } ICollection <OrderByNode> nodes = OrderByNodes; bool alreadyOrdered = false; IQueryable querySoFar = query; HashSet <IEdmProperty> propertiesSoFar = new HashSet <IEdmProperty>(); bool orderByItSeen = false; foreach (OrderByNode node in nodes) { OrderByPropertyNode propertyNode = node as OrderByPropertyNode; if (propertyNode != null) { IEdmProperty property = propertyNode.Property; OrderByDirection direction = propertyNode.Direction; // This check prevents queries with duplicate properties (e.g. $orderby=Id,Id,Id,Id...) from causing stack overflows if (propertiesSoFar.Contains(property)) { throw new ODataException(Error.Format(SRResources.OrderByDuplicateProperty, property.Name)); } propertiesSoFar.Add(property); if (propertyNode.OrderByClause != null) { // Ensure we have decided how to handle null propagation ODataQuerySettings updatedSettings = querySettings; if (querySettings.HandleNullPropagation == HandleNullPropagationOption.Default) { updatedSettings = new ODataQuerySettings(updatedSettings); updatedSettings.HandleNullPropagation = HandleNullPropagationOptionHelper.GetDefaultHandleNullPropagationOption(query); } LambdaExpression orderByExpression = FilterBinder.Bind(propertyNode.OrderByClause, Context.ElementClrType, Context.Model, updatedSettings); querySoFar = ExpressionHelpers.OrderBy(querySoFar, orderByExpression, direction, Context.ElementClrType, alreadyOrdered); } else { querySoFar = ExpressionHelpers.OrderByProperty(querySoFar, Context.Model, property, direction, Context.ElementClrType, alreadyOrdered); } alreadyOrdered = true; } else { // This check prevents queries with duplicate nodes (e.g. $orderby=$it,$it,$it,$it...) from causing stack overflows if (orderByItSeen) { throw new ODataException(Error.Format(SRResources.OrderByDuplicateIt)); } querySoFar = ExpressionHelpers.OrderByIt(querySoFar, node.Direction, Context.ElementClrType, alreadyOrdered); alreadyOrdered = true; orderByItSeen = true; } } return(querySoFar as IOrderedQueryable); }
private string convertDirection(OrderByDirection dir) { switch (dir) { case OrderByDirection.Ascending: return "asc"; case OrderByDirection.Descending: return "desc"; default: return "asc"; } }
public void AddThenByRequest(string propertyName, OrderByDirection direction) { thenByRequests.Add(propertyName, direction); }
public async Task <RepositoryResponse <PaginationModel <InfoProductViewModel> > > Search(string keyword = null, int?pageSize = null, int?pageIndex = null, string orderBy = "Id", OrderByDirection direction = OrderByDirection.Ascending) { Expression <Func <SiocProduct, bool> > predicate = model => model.Specificulture == _lang && model.Status != (int)SWStatus.Deleted && (string.IsNullOrWhiteSpace(keyword) || (model.Title.Contains(keyword) || model.Content.Contains(keyword))); var data = await InfoProductViewModel.Repository.GetModelListByAsync(predicate, orderBy, direction, pageSize, pageIndex).ConfigureAwait(false); // base.Search(predicate, orderBy, direction, pageSize, pageIndex, keyword); //if (data.IsSucceed) //{ // data.Data.Items.ForEach(d => d.DetailsUrl = string.Format("{0}{1}", _domain, this.Url.Action("Details", "products", new { id = d.Id }))); // data.Data.Items.ForEach(d => d.EditUrl = string.Format("{0}{1}", _domain, this.Url.Action("Edit", "products", new { id = d.Id }))); // data.Data.Items.ForEach(d => d.Domain = _domain); //} return(data); }