Example #1
0
        private async Task <PagingOutput <Schedule> > GetAllFilterAsync(IOrderedQueryable <Schedule> query, int page, int pageSize,
                                                                        SortOprions sort, string search = "")
        {
            if (search != "")
            {
                query = from _ in Context.Set <Schedule>()
                        where _.Personal.UserInfo.SurName.ToLower().Contains(search.ToLower()) ||
                        _.Personal.UserInfo.LastName.ToLower().Contains(search.ToLower()) ||
                        _.Personal.UserInfo.FirstName.ToLower().Contains(search.ToLower()) ||
                        _.Personal.UserInfo.PhoneNumber.ToLower().Contains(search.ToLower()) ||
                        _.Personal.UserInfo.Email.ToLower().Contains(search.ToLower()) ||
                        _.Personal.Polyclinic.Name.ToLower().Contains(search.ToLower()) ||
                        _.Personal.Position.Name.ToLower().Contains(search.ToLower()) ||
                        _.Personal.Polyclinic.Address.ToLower().Contains(search.ToLower())
                        orderby _.Id
                        select _;
            }

            switch (sort)
            {
            case SortOprions.Email:
                query = query.OrderBy(x => x.Personal.UserInfo.Email);
                break;

            case SortOprions.Email_desc:
                query = query.OrderByDescending(x => x.Personal.UserInfo.Email);
                break;

            case SortOprions.Name:
                query = query.OrderBy(x => x.Personal.UserInfo.FirstName);
                break;

            case SortOprions.Name_desc:
                query = query.OrderByDescending(x => x.Personal.UserInfo.FirstName);
                break;

            case SortOprions.Number:
                query = query.OrderBy(x => x.Id);
                break;

            case SortOprions.Number_desc:
                query = query.OrderByDescending(x => x.Id);
                break;

            case SortOprions.Position:
                query = query.OrderBy(x => x.Personal.Position.Name);
                break;

            case SortOprions.Position_desc:
                query = query.OrderByDescending(x => x.Personal.Position.Name);
                break;

            default:
                break;
            }

            return(await CommonRepositoryAsync.GetAllWithPageAsync(query, page, pageSize, _include));
        }
Example #2
0
        public static T[] ApplySortingPaging <T>(this IOrderedQueryable <T> query, SortingPagingDto sortingPaging)
        {
            var firstPass = true;

            foreach (var sortOrder in sortingPaging.SortOrders)
            {
                if (firstPass)
                {
                    firstPass = false;
                    query     = sortOrder.ColumnOrder == SortOrderDto.SortOrder.Ascending
                                ? query.OrderBy(sortOrder.ColumnName) :
                                query.OrderByDescending(sortOrder.ColumnName);
                }
                else
                {
                    query = sortOrder.ColumnOrder == SortOrderDto.SortOrder.Ascending
                                ? query.ThenBy(sortOrder.ColumnName) :
                            query.ThenByDescending(sortOrder.ColumnName);
                }
            }

            var result = query.Skip((sortingPaging.PageNumber - 1) *
                                    sortingPaging.NumberRecords).Take(sortingPaging.NumberRecords).ToArray();

            return(result);
        }
Example #3
0
        public static IOrderedQueryable <T> ApplyOrder <T>(this IOrderedQueryable <T> query, string orderColumn,
                                                           SortDirection sortDirection)
        {
            Tracer.Verbose(() => "applying query order");

            if (string.IsNullOrEmpty(orderColumn))
            {
                return(query);
            }

            switch (sortDirection)
            {
            case SortDirection.Ascending:
                Tracer.Verbose(() => "ascending order");
                return(query.OrderBy(orderColumn));

            case SortDirection.Descending:
                Tracer.Verbose(() => "descending order");
                return(query.OrderByDescending(orderColumn));

            default:
                Tracer.Verbose(() => "no ordering applied");
                return(query);
            }
        }
Example #4
0
        private IOrderedQueryable<Book> Sort(
            IOrderedQueryable<Book> books)
        {
            IOrderedQueryable<Book> orderedBooks = books.OrderBy(b => b.Title);

            return orderedBooks;
        }
        public IOrderedQueryable <Aluno> OrdernarGrid(string sortOrder, IOrderedQueryable <Aluno> aluno)
        {
            switch (sortOrder)
            {
            case "nomeDesc":
                aluno = aluno.OrderByDescending(x => x.Nome);
                break;

            case "cpfDesc":
                aluno = aluno.OrderByDescending(x => x.Cpf);
                break;

            case "dataDesc":
                aluno = aluno.OrderByDescending(x => x.DataCadastro);
                break;

            case "dataCadastro":
                aluno = aluno.OrderBy(x => x.DataCadastro);
                break;

            case "sexoDesc":
                aluno = aluno.OrderByDescending(x => x.Sexo);
                break;

            case "cidadeDesc":
                aluno = aluno.OrderByDescending(x => x.Endereco.Cidade.Nome);
                break;
            }

            return(aluno);
        }
        private IOrderedQueryable <Book> Sort(
            IOrderedQueryable <Book> books)
        {
            IOrderedQueryable <Book> orderedBooks = books.OrderBy(b => b.Title);

            return(orderedBooks);
        }
        public static IOrderedQueryable <T> SortBy <T, TKey>(
            this IQueryable <T> source,
            IEnumerable <Sort> sort,
            Expression <Func <T, TKey> > defaultSort,
            SortDirection defaultSortDirection = SortDirection.Asc)
        {
            IOrderedQueryable <T> source1          = (IOrderedQueryable <T>)source;
            List <Sort>           scrubbedSortList = SortByExtensions.GetScrubbedSortList <T>(sort);

            if (!scrubbedSortList.Any <Sort>())
            {
                if (defaultSortDirection != SortDirection.Desc)
                {
                    return(source1.OrderBy <T, TKey>(defaultSort));
                }
                return(source1.OrderByDescending <T, TKey>(defaultSort));
            }
            for (int index = 0; index < scrubbedSortList.Count; ++index)
            {
                Sort   sort1   = scrubbedSortList[index];
                string keyword = (index == 0 ? "OrderBy" : "ThenBy") + (sort1.Direction == SortDirection.Desc ? "Descending" : string.Empty);
                source1 = source1.SortOrderedQueryableBy <T>(sort1.Name, keyword);
            }
            return(source1);
        }
        public virtual Task <IEnumerable <TEntity> > GetAllPagedAsync(Expression <Func <TEntity, bool> > predicate, int pageNumber, int itemsPerPage, bool ascending = true, params Expression <Func <TEntity, object> >[] sortingExpression)
        {
            IOrderedQueryable <TEntity> orderedQuery = null;

            if (ascending)
            {
                orderedQuery = GetAll().Where(predicate).OrderBy(sortingExpression[0]);
                for (int i = 1; i < sortingExpression.Length; i++)
                {
                    orderedQuery = orderedQuery.OrderBy(sortingExpression[i]);
                }
            }
            else
            {
                orderedQuery = GetAll().Where(predicate).OrderByDescending(sortingExpression[0]);
                for (int i = 1; i < sortingExpression.Length; i++)
                {
                    orderedQuery = orderedQuery.OrderByDescending(sortingExpression[i]);
                }
            }

            var entities = orderedQuery.Skip((pageNumber + 1) * itemsPerPage)
                           .Take(itemsPerPage)
                           .AsEnumerable();

            return(Task.FromResult(entities));
        }
Example #9
0
        private void ApplySort(ref IOrderedQueryable <Owner> owners, string orderByQueryString)
        {
            if (!owners.Any())
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(orderByQueryString))
            {
                owners = owners.OrderBy(x => x.Name);
                return;
            }

            var orderParams       = orderByQueryString.Trim().Split(',');
            var propertyInfos     = typeof(Owner).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            var orderQueryBuilder = new StringBuilder();

            foreach (var param in orderParams)
            {
                if (string.IsNullOrWhiteSpace(param))
                {
                    continue;
                }

                var propertyFromQueryName = param.Split(" ")[0];
                var objectProperty        = propertyInfos.FirstOrDefault(pi => pi.Name.Equals(propertyFromQueryName, StringComparison.InvariantCultureIgnoreCase));

                if (objectProperty == null)
                {
                    continue;
                }

                var sortingOrder = param.EndsWith(" desc") ? "descending" : "ascending";

                orderQueryBuilder.Append($"{objectProperty.Name.ToString()} {sortingOrder}, ");
            }

            var orderQuery = orderQueryBuilder.ToString().TrimEnd(',', ' ');

            if (string.IsNullOrWhiteSpace(orderQuery))
            {
                owners = owners.OrderBy(x => x.Name);
                return;
            }

            owners = owners.OrderBy(orderQuery);
        }
Example #10
0
 protected virtual IOrderedQueryable <MessageEntity> ApplyOrderByDatePosted(IOrderedQueryable <MessageEntity> queryable, int index)
 {
     if (index == 0)
     {
         return(queryable.OrderBy(message => message.DatePosted));
     }
     return(queryable.ThenBy(message => message.DatePosted));
 }
 public static IOrderedQueryable <T> AddOrdering <T, TKey>(this IOrderedQueryable <T> source, Expression <Func <T, TKey> > keySelector, bool descending)
 {
     if (source.Expression.Type != typeof(IOrderedQueryable <T>))
     {
         return(descending ? source.OrderByDescending(keySelector) : source.OrderBy(keySelector));
     }
     return(descending ? ((IOrderedQueryable <T>)source).ThenByDescending(keySelector) : ((IOrderedQueryable <T>)source).ThenBy(keySelector));
 }
        public IOrderedConfigurableQuery <TEntity, TModel> OrderBy <TKey>(Expression <Func <TEntity, TKey> > expression)
        {
            if (IsValid)
            {
                mDbQuery = mDbQuery.OrderBy(expression);
            }

            return(this);
        }
Example #13
0
 public static IOrderedQueryable <TSource> ThenBy <TSource, TKey>(
     this IOrderedQueryable <TSource> source,
     Expression <Func <TSource, TKey> > keySelector,
     bool ascending)
 {
     return(ascending
         ? source.OrderBy(keySelector)
         : source.OrderByDescending(keySelector));
 }
Example #14
0
        //Admin ->get list user
        public IEnumerable <User> ListAllPaging(string searchString, int page, int pagesize)
        {
            IOrderedQueryable <User> model = db.Users;

            if (!string.IsNullOrEmpty(searchString))
            {
                model = model.Where(x => x.UserName.Contains(searchString) || x.Name.Contains(searchString)).OrderBy(x => x.ID);
            }
            return(model.OrderBy(x => x.ID).ToPagedList(page, pagesize));
        }
        public static IOrderedQueryable <TEntity> ApplyOrdering <TEntity>(this IQueryable <TEntity> query, Dictionary <string, Expression <Func <TEntity, object> > > columnsMap, string multipleSortBy)
        {
            IOrderedQueryable <TEntity> orderedQuery = (IOrderedQueryable <TEntity>)query;
            var orderByList = multipleSortBy.Split(',');

            if (!orderByList.Any())
            {
                return(orderedQuery);
            }

            var orderBy = orderByList[0];
            var prop    = orderBy.Split(' ')[0];

            if (orderBy.Split(' ')[1] == "asc" && columnsMap.ContainsKey(prop))
            {
                orderedQuery = orderedQuery.OrderBy(columnsMap[prop]);
            }
            else if (columnsMap.ContainsKey(prop))
            {
                orderedQuery = orderedQuery.OrderByDescending(columnsMap[prop]);
            }
            else
            {
                orderedQuery = orderedQuery.OrderBy(x => x);
            }

            for (int i = 1; i < orderByList.Length; i++)
            {
                orderBy = orderByList[i];
                prop    = orderBy.Split(' ')[0];

                if (orderBy.Split(' ')[1] == "asc" && columnsMap.ContainsKey(prop))
                {
                    orderedQuery = orderedQuery.ThenBy(columnsMap[prop]);
                }
                else if (columnsMap.ContainsKey(prop))
                {
                    orderedQuery = orderedQuery.ThenByDescending(columnsMap[prop]);
                }
            }

            return(orderedQuery);
        }
        //Admin
        public IEnumerable <Category> ListAll(string searchString, int page, int pagesize)
        {
            IOrderedQueryable <Category> model = db.Categories;

            if (!string.IsNullOrEmpty(searchString))
            {
                model = model.Where(x => x.Name.Contains(searchString)).OrderBy(x => x.ID);
            }
            return(model.OrderBy(x => x.CreateDate).ToPagedList(page, pagesize));
        }
Example #17
0
            /// <summary>
            /// Creates Ordered query based on stored expressions and delegates.
            /// For row columns that have identical names with db columns, the order is made automatically
            /// </summary>
            /// <param name="query">Query that will be ordered</param>
            /// <param name="defaultOrderFunc">Default order row column. The query must be ordered before take/skip</param>
            /// <returns>Ordered query</returns>
            public IOrderedQueryable <TEntity> Order(IQueryable <TEntity> query, Func <IQueryable <TEntity>, IOrderedQueryable <TEntity> > defaultOrderFunc)
            {
                //throw exception if defaultOrder is not asc or desc
                if (defaultOrderFunc == null)
                {
                    throw new Exception("you must implement a func for default order");
                }

                IOrderedQueryable <TEntity> orderedQuery = defaultOrderFunc(query);

                if (this.columnsOrder != null && this.columnsOrder.Any())
                {
                    this.columnsOrder.Reverse();

                    //order dict desc and order query based on Order priority
                    foreach (var item in this.columnsOrder)
                    {
                        var name = item.Name;

                        if (this.expressionSettings.ContainsKey(name))
                        {
                            var criteria = this.expressionSettings[name];

                            if (item.Type == BsOrderType.Ascending)
                            {
                                orderedQuery = criteria.OrderBy(orderedQuery);
                            }
                            else if (item.Type == BsOrderType.Descending)
                            {
                                orderedQuery = criteria.OrderByDescending(orderedQuery);
                            }

                            continue;
                        }

                        if (this.delegateSettings.ContainsKey(name))
                        {
                            orderedQuery = this.delegateSettings[name](orderedQuery, item.Type);

                            continue;
                        }

                        if (item.Type == BsOrderType.Ascending)
                        {
                            orderedQuery = orderedQuery.OrderBy(name);
                        }
                        else if (item.Type == BsOrderType.Descending)
                        {
                            orderedQuery = orderedQuery.OrderByDescending(name);
                        }
                    }
                }

                return(orderedQuery);
            }
Example #18
0
        public static IOrderedQueryable <T> AddOrderBy <T, TKey>(this IOrderedQueryable <T> q,
                                                                 Expression <Func <T, TKey> > orderExpression, bool isDescending = false)
        {
            var hasBeenOrdered = q.IsOrdered();

            if (hasBeenOrdered)
            {
                return(!isDescending?q.ThenBy(orderExpression) : q.ThenByDescending(orderExpression));
            }
            return(!isDescending?q.OrderBy(orderExpression) : q.OrderByDescending(orderExpression));
        }
        //admin
        public IEnumerable <OrderDetail> ListAll(string searchString, int page, int pagesize)
        {
            IOrderedQueryable <OrderDetail> model = db.OrderDetails;

            if (!string.IsNullOrEmpty(searchString))
            {
                model = model.Where(/*x => x.ProductID.ToString().Contains(searchString) ||*/ x => x.OrderID.ToString().Contains(searchString)
                                    /*|| x.Quantity.ToString().Contains(searchString) || x.Price.ToString().Contains(searchString)*/).OrderBy(x => x.OrderID);
            }
            return(model.OrderBy(x => x.OrderID).ToPagedList(page, pagesize));
        }
        public IEnumerable <Order> ListAll(string searchString, int page, int pagesize)
        {
            IOrderedQueryable <Order> model = db.Orders;

            if (!string.IsNullOrEmpty(searchString))
            {
                model = model.Where(x => x.ShipName.Contains(searchString) || x.ShipAddress.Contains(searchString) ||
                                    x.ShipEmail.Contains(searchString) || x.ShipMobile.Contains(searchString) ||
                                    x.ID.ToString().Contains(searchString)).OrderBy(x => x.ID);
            }
            return(model.OrderBy(x => x.ID).ToPagedList(page, pagesize));
        }
Example #21
0
    public IQueryable <Category> List(int startIndex, int count)
    {
        NorthwindEntities            ent   = new NorthwindEntities();
        IOrderedQueryable <Category> query = ent.CategorySet;

        ProvideDefaultSorting(ref query);
        if (!PartialMethodHasNotRun)
        {
            query = query.OrderBy(c => c.CategoryID);
        }
        return(query.Skip(startIndex).Take(count));
    }
Example #22
0
 protected override IOrderedQueryable <Person> AddSortAscending(IOrderedQueryable <Person> query, string propertyName, bool isFirstSort)
 {
     if (propertyName == "FirstName")
     {
         if (isFirstSort == true)
         {
             return(query.OrderBy(x => x.FirstName));
         }
         else
         {
             return(query.ThenBy(x => x.FirstName));
         }
     }
     else if (propertyName == "LastName")
     {
         if (isFirstSort == true)
         {
             return(query.OrderBy(x => x.LastName));
         }
         else
         {
             return(query.ThenBy(x => x.LastName));
         }
     }
     else if (propertyName == "Id")
     {
         if (isFirstSort == true)
         {
             return(query.OrderBy(x => x.Id));
         }
         else
         {
             return(query.ThenBy(x => x.Id));
         }
     }
     else
     {
         return(null);
     }
 }
    public IQueryable <Category> List(int startIndex, int count)
    {
        NorthwindEntities            ent   = new NorthwindEntities();
        IOrderedQueryable <Category> query = ent.CategorySet;
        var oldQuery = query;

        ProvideDefaultSorting(ref query);
        if (oldQuery.Equals(query))         // the partial method did nothing with the query, or just didn't exist
        {
            query = query.OrderBy(c => c.CategoryID);
        }
        return(query.Skip(startIndex).Take(count));
    }
        public static IOrderedQueryable <T> OrderByString <T>(this IQueryable <T> source, string orderBy)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrWhiteSpace(orderBy))
            {
                throw new ArgumentNullException(nameof(orderBy));
            }

            IOrderedQueryable <T> result = null;

            // the orderBy string is separated by ",", so we split it.
            var orderByAfterSplit = orderBy.Split(',');

            // apply each orderby clause in reverse order - otherwise, the
            // IQueryable will be ordered in the wrong order
            foreach (var orderByClause in orderByAfterSplit.Reverse())
            {
                // trim the orderBy clause, as it might contain leading
                // or trailing spaces. Can't trim the var in foreach,
                // so use another var.
                var trimmedOrderByClause = orderByClause.Trim();

                // if the sort option ends with with " desc", we order
                // descending, ortherwise ascending
                var orderDescending = trimmedOrderByClause.EndsWith(" desc");

                // remove " asc" or " desc" from the orderBy clause, so we
                // get the property name to look for in the mapping dictionary
                var indexOfFirstSpace = trimmedOrderByClause.IndexOf(" ");
                var propertyName      = indexOfFirstSpace == -1 ?
                                        trimmedOrderByClause : trimmedOrderByClause.Remove(indexOfFirstSpace);

                if (result == null)
                {
                    result = source.OrderBy(propertyName +
                                            (orderDescending ? " descending" : " ascending"));
                }
                else
                {
                    result = result.OrderBy(propertyName +
                                            (orderDescending ? " descending" : " ascending"));
                }
            }

            return(result);
        }
 /// <summary>
 /// The ThenBy.
 /// </summary>
 /// <typeparam name="TSource">.</typeparam>
 /// <typeparam name="TKey">.</typeparam>
 /// <param name="source">The source<see cref="IOrderedQueryable{TSource}"/>.</param>
 /// <param name="keySelector">The keySelector<see cref="System.Linq.Expressions.Expression{Func{TSource, TKey}}"/>.</param>
 /// <param name="sortOrder">The sortOrder<see cref="SortDirection"/>.</param>
 /// <param name="comparer">The comparer<see cref="IComparer{TKey}"/>.</param>
 /// <returns>The <see cref="IOrderedQueryable{TSource}"/>.</returns>
 public static IOrderedQueryable <TSource> ThenBy <TSource, TKey>(this IOrderedQueryable <TSource> source,
                                                                  System.Linq.Expressions.Expression <Func <TSource, TKey> > keySelector,
                                                                  SortDirection sortOrder, IComparer <TKey> comparer
                                                                  )
 {
     if (sortOrder == SortDirection.ASC)
     {
         return(source.OrderBy(keySelector));
     }
     else
     {
         return(source.OrderByDescending(keySelector));
     }
 }
Example #26
0
 /// <summary>
 /// Orders the IQueryable using the linq sorter.
 /// </summary>
 /// <typeparam name="T">The type to order.</typeparam>
 /// <param name="source">The queryable source.</param>
 /// <param name="sorters">The linq sortera.</param>
 /// <returns>The ordered IQueryable.</returns>
 public static IOrderedQueryable <T> OrderBy <T>(this IQueryable <T> source, IEnumerable <LinqSorter <T> > sorters) where T : class
 {
     Contract.Requires(source != null, "The source must not be null.");
     Contract.Requires(sorters != null, "The sorters must not be null.");
     using (var enumerator = sorters.GetEnumerator())
     {
         IOrderedQueryable <T> orderedQuery = null;
         while (enumerator.MoveNext())
         {
             var sorter = enumerator.Current;
             if (orderedQuery == null)
             {
                 if (sorter.Direction == SortDirection.Ascending)
                 {
                     orderedQuery = source.OrderBy(sorter, "OrderBy");
                 }
                 else
                 {
                     orderedQuery = source.OrderBy(sorter, "OrderByDescending");
                 }
             }
             else
             {
                 Debug.Assert(orderedQuery != null, "The ordered query should be initialized.");
                 if (sorter.Direction == SortDirection.Ascending)
                 {
                     orderedQuery = orderedQuery.OrderBy(sorter, "ThenBy");
                 }
                 else
                 {
                     orderedQuery = orderedQuery.OrderBy(sorter, "ThenByDescending");
                 }
             }
         }
         return(orderedQuery);
     }
 }
Example #27
0
        /// <summary>
        /// 排序
        /// </summary>
        /// <returns></returns>
        private IOrderedQueryable <DetailInfo> order(IOrderedQueryable <DetailInfo> list, string orderfield, int sortorder)
        {
            switch (orderfield.ToLower())
            {
            case "hitsnum":
                if (sortorder == 0)
                {
                    return(list.OrderBy(g => g.HitsNum));
                }
                else
                {
                    return(list.OrderByDescending(g => g.HitsNum));
                }

            case "agreenum":
                if (sortorder == 0)
                {
                    return(list.OrderBy(g => g.AgreeNum));
                }
                else
                {
                    return(list.OrderByDescending(g => g.AgreeNum));
                }

            case "follownum":
                if (sortorder == 0)
                {
                    return(list.OrderBy(g => g.FollowNum));
                }
                else
                {
                    return(list.OrderByDescending(g => g.FollowNum));
                }
            }
            return(list);
        }
Example #28
0
        public static List <TEntity> List(Expression <Func <TEntity, bool> > filter, List <SortDescriptor> sortDescriptors, int skip, int take, out int total, params string[] includes)
        {
            List <TEntity> items      = null;
            int            localTotal = 0;

            OnDb((context, table) => {
                DbQuery <TEntity> entity = table;
                if (includes != null && includes.Length > 0)
                {
                    foreach (string include in includes)
                    {
                        entity = entity.Include(include);
                    }
                }
                IQueryable <TEntity> query;
                if (filter == null)
                {
                    query = entity;
                }
                else
                {
                    query = entity.Where(filter);
                }

                if (sortDescriptors != null && sortDescriptors.Count > 0)
                {
                    IOrderedQueryable <TEntity> ordered = null;
                    foreach (var sortDescriptor in sortDescriptors)
                    {
                        if (ordered == null)
                        {
                            ordered = query.OrderBy(sortDescriptor.Field, sortDescriptor.Dir == "desc");
                        }
                        else
                        {
                            ordered = ordered.OrderBy(sortDescriptor.Field, sortDescriptor.Dir == "desc");
                        }
                    }
                    query = ordered;
                }

                localTotal = query.Count();
                items      = query.Skip(skip).Take(take).ToList();
            });
            total = localTotal;
            return(items);
        }
Example #29
0
        public static IOrderedQueryable <T> OrderExpressionToOrderedQueryable <T>(this IQueryable <T> query, IOrder <T> order) where T : BaseEntity
        {
            var orderSelector = order.Getstock();

            if (orderSelector == null || orderSelector.Count() == 0)
            {
                return(query.OrderBy(t => true));
            }
            else if (orderSelector.Values.Count == 1)
            {
                var orderExpression = orderSelector.First();
                if (orderExpression.Value == QueryOrderBy.Asc)
                {
                    return(query.OrderBy(orderExpression.Key));
                }
                else
                {
                    return(query.OrderByDescending(orderExpression.Key));
                }
            }
            else
            {
                IOrderedQueryable <T> orderQuery = null;
                var firstOrderExpression         = orderSelector.First();
                if (firstOrderExpression.Value == QueryOrderBy.Asc)
                {
                    orderQuery = query.OrderBy(firstOrderExpression.Key);
                }
                else
                {
                    orderQuery = query.OrderByDescending(firstOrderExpression.Key);
                }
                foreach (var orderExpression in orderSelector)
                {
                    if (orderExpression.Value == QueryOrderBy.Asc)
                    {
                        orderQuery = orderQuery.OrderBy(orderExpression.Key);
                    }
                    else
                    {
                        orderQuery = orderQuery.OrderByDescending(orderExpression.Key);
                    }
                }
                return(orderQuery);
            }
        }
Example #30
0
        public static IOrderedQueryable <TSource> SortBy <TSource, TKey>(
            this IOrderedQueryable <TSource> source,
            Expression <Func <TSource, TKey> > keySelector,
            SortDirection direction,
            int sortIndex)
        {
            if (sortIndex == 0)
            {
                return(direction == SortDirection.Asc
                    ? source.OrderBy(keySelector)
                    : source.OrderByDescending(keySelector));
            }

            return(direction == SortDirection.Asc
                ? source.ThenBy(keySelector)
                : source.ThenByDescending(keySelector));
        }
        public static IOrderedQueryable <TEntity> ApplyOrdering <TEntity>(this IQueryable <TEntity> query, Dictionary <string, Expression <Func <TEntity, object> > > columnsMap, string sortBy, bool isAsc = true)
        {
            IOrderedQueryable <TEntity> orderedQuery = (IOrderedQueryable <TEntity>)query;

            if (string.IsNullOrEmpty(sortBy) || columnsMap == null || !columnsMap.ContainsKey(sortBy))
            {
                return(orderedQuery);
            }

            if (isAsc)
            {
                return(orderedQuery.OrderBy(columnsMap[sortBy]));
            }
            else
            {
                return(orderedQuery.OrderByDescending(columnsMap[sortBy]));
            }
        }
        // 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;
        }