Example #1
0
        public static List<Models.GameContext.Guild> GetRankings(int topNumber = 0, Models.GameContext.GuildRankingOrderBy orderBy = GuildRankingOrderBy.Score)
        {
            List<Models.GameContext.Guild> guilds = new List<Models.GameContext.Guild>();

            using (var context = new GameDbContext())
            {
                guilds = context.Guilds.ToList();

                if(orderBy == GuildRankingOrderBy.Name)
                {
                    guilds = guilds.OrderByDescending(x => x.G_Name).ToList();
                }

                if(orderBy == GuildRankingOrderBy.Score)
                {
                    guilds = guilds.OrderByDescending(x => x.G_Score).ToList();
                }

                if(topNumber > 0)
                {
                    guilds = guilds.Take(topNumber).ToList();
                }
            }

            return guilds;
        }
Example #2
0
        static void Main(string[] args)
        {
            var products = new List<string>() {"Basketball", "Baseball", "Tennis Raquet", "Running Shoes", "Wrestling Shoes", "Soccer Ball", "Football", "Shoulder Pads",
                "Trail Running Shoes", "Cycling Shoes", "Kayak", "Kayak Paddles", "shoes1", "shoes2"};

            //declare a variable kayakProducts and set it equal to all products that contain the word "Kayak"
            var kayakProducts = products.Where(x => x.Contains("Kayak"));
            //print the kayakProducts to the console using a foreach loop.
            foreach (string item in kayakProducts)
            {
                Console.WriteLine(item);
            }
            //single line solution.  "\n" is a line break.
            Console.WriteLine(string.Join("\n", kayakProducts));

            //declare a variable shoeProducts and set it equal to all products that contain the word "Shoes"
            var shoeProducts = products.Where(x => x.Contains("Shoes")).ToList();

            //print the shoeProducts to the console using a foreach loop.
            Console.WriteLine(string.Join(", ", shoeProducts));

            //declare a variable ballProducts and set it equal to all the products that have ball in the name.
            var ballProducts = products.Where(x => x.ToLower().Contains("ball"));

            //print the ballProducts to the console using a foreach loop.
            Console.WriteLine(string.Join(", ", ballProducts));

            //sort ballProducts alphabetically and print them to the console.
            Console.WriteLine(string.Join(", ", ballProducts.OrderBy(x => x)));

            //add six more items to the products list using .add().
            //add multiple products individually, but on the same line
            products.Add("ice axe"); products.Add("crampons"); products.Add("trekking poles");
            //add multiple products at the same time
            products.AddRange(new List<string>() { "baseball bases", "baseball helmet" });

            Console.WriteLine(string.Join(", ", ballProducts.OrderBy(x => x)));

            //print the product with the longest name to the console using the .First() extension.
            Console.WriteLine(products.OrderByDescending(x => x.Length).First());
            //print the product with the shortest name to the console using the .Last() extension.
            Console.WriteLine(products.OrderByDescending(x => x.Length).Last());

            //print the product with the 4th shortest name to the console using an index (you must convert the results to a list using .ToList()).
            Console.WriteLine(products.OrderBy(x => x.Length).Skip(3).Take(1).First());

            //print the ballProduct with the 2nd longest name to the console using an index(you must convert the results to a list using .ToList()).
            Console.WriteLine(ballProducts.OrderByDescending(x => x.Length).ToList()[1]);

            //declare a variable reversedProducts and set it equal to all products ordered by the longest word first. (use the OrderByDecending() extension).

            //print out the reversedProducts to the console using a foreach loop.

            //print out all the products ordered by the longest word first using the OrderByDecending() extension and a foreach loop.
            //You will not use a variable to store your list

            Console.WriteLine(string.Join(", ", products.OrderByDescending(x => x.Length).ThenBy(x=> x)));

            Console.ReadKey();
        }
Example #3
0
        public List<Car> SortCars(string sortOrder, List<Car> carsList)
        {
            List<Car> SortedList;
            switch (sortOrder)
            {
                case "price":
                    {
                        SortedList = carsList.OrderBy(o => o.Price).ToList();
                        break;
                    }
                case "mileage":
                    {
                        SortedList = carsList.OrderBy(o => o.Mileage).ToList();
                        break;
                    }
                case "price_desc":
                    {
                        SortedList = carsList.OrderByDescending(o => o.Price).ToList();
                        break;
                    }
                case "mileage_desc":
                    {
                        SortedList = carsList.OrderByDescending(o => o.Mileage).ToList();
                        break;
                    }
                default:

                    SortedList = carsList;
                    break;
            }
            return SortedList;
        }
Example #4
0
        private void AjustarBindServicos(List<ServicoDTO> servicos)
        {
            if (servicos.OrderByDescending(q => q.idServico).FirstOrDefault() != null)
                idServicoAux = servicos.OrderByDescending(q => q.idServico).FirstOrDefault().idServico;

            dgvServicos.DataSource = servicos;
            dgvServicos.Columns[0].Visible = false;
            dgvServicos.Columns[1].Visible = false;
            dgvServicos.Columns[2].Visible = false;
            dgvServicos.Columns[3].Visible = false;
            dgvServicos.Columns[4].Visible = false;
            dgvServicos.Columns[12].Visible = false;
            dgvServicos.Columns[13].Visible = false;
            dgvServicos.Columns[14].Visible = false;
            dgvServicos.Columns[15].Visible = false;
            dgvServicos.Columns[16].Visible = false;

            dgvServicos.Columns[6].HeaderText = "Entrega pelo";
            dgvServicos.Columns[7].HeaderText = "Objetos Declarados";
            dgvServicos.Columns[7].Width = 300;
            dgvServicos.Columns[8].HeaderText = "Observação do Cliente";
            dgvServicos.Columns[8].Width = 300;
            dgvServicos.Columns[9].HeaderText = "Status Serviço";
            dgvServicos.Columns[11].HeaderText = "Serviço";

            dgvServicos.Columns[10].DataPropertyName = "dtInicio";
            dgvServicos.Columns[10].HeaderText = "Início";
            dgvServicos.Columns[10].Width = 120;

            dgvServicos.Columns[12].DataPropertyName = "dtFim";
            dgvServicos.Columns[12].HeaderText = "Fim";
            dgvServicos.Columns[12].Width = 120;
        }
        protected static List<Comment> GetTopCommentList(Comment[] allComments)
        {
            List<Comment> topComments = new List<Comment>();

            foreach (Comment comment in allComments)
            {
                // Builds and sorts empty list until sufficiently large
                if (topComments.Count() < TOP_COMMENTS_TO_GRAB)
                {
                    topComments.Add(comment);
                    topComments = topComments.OrderByDescending(c => c.Upvotes).ToList();
                }
                else
                {
                    foreach (Comment topComment in topComments)
                    {
                        if (comment.Upvotes > topComment.Upvotes)
                        {
                            // Compares comment against descending list and then re-sorts once inserted
                            topComments.Remove(topComment);
                            topComments.Add(comment);
                            topComments = topComments.OrderByDescending(c => c.Upvotes).ToList();
                            break;
                        }
                    }
                }
            }

            return topComments;
        }
Example #6
0
        /// <summary>
        /// Sets the player type if his hand type is four of a kind.
        /// </summary>
        public void FourOfAKind(IPlayer player, int[] straight, List<Type> winners, ref Type sorted)
        {
            if (player.HandType >= -1)
            {
                for (int j = 0; j <= 3; j++)
                {
                    if (straight[j] / 4 == straight[j + 1] / 4 && straight[j] / 4 == straight[j + 2] / 4
                        && straight[j] / 4 == straight[j + 3] / 4)
                    {
                        player.HandType = 7;
                        player.HandPower = (straight[j] / 4) * 4 + player.HandType * 100;
                        winners.Add(new Type() { Power = player.HandPower, Current = 7 });
                        sorted = winners.OrderByDescending(op1 => op1.Current).ThenByDescending(op1 => op1.Power).First();
                    }

                    if (straight[j] / 4 == 0 && straight[j + 1] / 4 == 0 && straight[j + 2] / 4 == 0
                        && straight[j + 3] / 4 == 0)
                    {
                        player.HandType = 7;
                        player.HandPower = (13 * 4) + (player.HandType * 100);
                        winners.Add(new Type() { Power = player.HandPower, Current = 7 });
                        sorted = winners.OrderByDescending(op1 => op1.Current).ThenByDescending(op1 => op1.Power).First();
                    }
                }
            }
        }
Example #7
0
        public ActionResult Index(int? page, int? PageSize, string sortBy)
        {
            var customers = new List<DSC_CUSTOMER>();
            var viewCustomers = new List<CustViewModel>();
            ViewBag.CurrentItemsPerPage = PageSize ?? 10;
            ViewBag.SortNameParameter = String.IsNullOrEmpty(sortBy) ? "Name desc" : "Name";
            ViewBag.SortParentParameter = sortBy == "Parent" ? "Parent desc" : "Parent"; 

            using (DSC_OBS_DB_ENTITY db = new DSC_OBS_DB_ENTITY())
            {
                customers = db.DSC_CUSTOMER.Where(cust_id => cust_id.dsc_cust_id > 0).ToList();
            }
            //DateTime active_date;
            foreach (DSC_CUSTOMER customer in customers)
            {
                string activeAction = "";
                try
                {
                    if (customer.dsc_cust_eff_end_date == null)
                    {
                        activeAction = "YES";

                    }//end of if
                    else
                    {
                        if (customer.dsc_cust_eff_end_date <= DateTime.Today)
                        {
                            activeAction = "NO";
                        }
                        else
                        {
                            activeAction = "YES";
                        }
                    }//end of else
                }//end of try
                catch
                {
                    activeAction = "NO";
                }//end of catch

                viewCustomers.Add(new CustViewModel(customer.dsc_cust_id, customer.dsc_cust_name, customer.dsc_cust_parent_name, activeAction, activeAction == "YES" ? "Deactivate" : "Activate"));
            }// end of foreach
            switch (sortBy)
            {
                case "Name desc":
                    return View(viewCustomers.OrderByDescending(x=>x.dsc_cust_name).ToPagedList(page ?? 1, PageSize ?? 10));
                case "Parent desc":
                    return View(viewCustomers.OrderByDescending(x => x.dsc_cust_parent_name).ToPagedList(page ?? 1, PageSize ?? 10));
                case"Name":
                    return View(viewCustomers.OrderBy(x => x.dsc_cust_name).ToPagedList(page ?? 1, PageSize ?? 10));
                case "Parent":
                    return View(viewCustomers.OrderBy(x => x.dsc_cust_parent_name).ToPagedList(page ?? 1, PageSize ?? 10));
                default: return View(viewCustomers.ToPagedList(page ?? 1, PageSize ?? 10));


            }

            
            
        }
        public JsonResult GetUserOrders(int type,string userid, string teamid, string beginTime, string endTime,string ordertype)
        {

            var list = SalesRPTBusiness.BaseBusiness.GetUserOrders(userid, teamid, beginTime, endTime, CurrentUser.AgentID, CurrentUser.ClientID, ordertype);

            if (type == 2)
            {
                Dictionary<string, List<TypeOrderEntity>> customerlist =  new Dictionary<string, List<TypeOrderEntity>>(); 
                
                List<TypeOrderEntity> listcustomer = new List<TypeOrderEntity>();
                list.ForEach(x => listcustomer.AddRange(x.ChildItems));
                customerlist.Add("TotalList", listcustomer.OrderByDescending(x =>  x.TCount).Take(15).ToList());
                customerlist.Add("MoneyList", listcustomer.OrderByDescending(x =>  x.TMoney).Take(15).ToList());
                JsonDictionary.Add("items", customerlist);
            }
            else
            {
                JsonDictionary.Add("items", list);
            }
            return new JsonResult()
            {
                Data = JsonDictionary,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        public JqGridData FetchListOfChildren(Person currentPerson, JqGridRequest request, string[] selectedRoles)
        {
            IEnumerable<ChildReportDto> listOfChildren = new List<ChildReportDto>();
            try
            {
                listOfChildren = _childrenReportsRepository.GetListOfChildrenForAChurch(currentPerson, ConversionService.ConvertSelectedRolesToListOfInts(selectedRoles));
            }
            catch (Exception ex)
            {
                _emailService.SendExceptionEmail(ex);
            }

            var totalRecords = listOfChildren.Count();

            switch (request.sidx)
            {
                case "Age":
                    {
                        listOfChildren = request.sord.ToLower() == "asc" ? listOfChildren.OrderBy(p => p.Age).Skip((request.page - 1) * request.rows).Take(request.rows) : listOfChildren.OrderByDescending(p => p.Age).Skip((request.page - 1) * request.rows).Take(request.rows);
                        break;
                    }
                case "Surname":
                    {
                        listOfChildren = request.sord.ToLower() == "asc" ? listOfChildren.OrderBy(p => p.Surname).Skip((request.page - 1) * request.rows).Take(request.rows) : listOfChildren.OrderByDescending(p => p.Surname).Skip((request.page - 1) * request.rows).Take(request.rows);
                        break;
                    }
                case "Firstname":
                    {
                        listOfChildren = request.sord.ToLower() == "asc" ? listOfChildren.OrderBy(p => p.Firstname).Skip((request.page - 1) * request.rows).Take(request.rows) : listOfChildren.OrderByDescending(p => p.Firstname).Skip((request.page - 1) * request.rows).Take(request.rows);
                        break;
                    }
            }

            var childrenGridData = new JqGridData()
            {
                total = (int) Math.Ceiling((float) totalRecords/request.rows),
                page = request.page,
                records = totalRecords,
                rows = (from p in listOfChildren.AsEnumerable()
                    select new JqGridRow()
                    {
                        id = p.PersonId.ToString(),
                        cell = new[]
                        {
                            p.PersonId.ToString(),
                            p.Age.ToString(),
                            p.Firstname,
                            p.Surname,
                            p.CellNo,
                            p.GroupName,
                            p.Father,
                            p.Mother

                        }
                    }).ToArray()
            };

            return childrenGridData;
        }
Example #10
0
        public void Execute()
        {
            var persons = new List<Person>
            {
                new Person {Id = 1001, Name = "gsf_zero1"},
                new Person {Id = 1000, Name = "gsf_zero2"},
                new Person {Id = 111, Name = "gsf_zero3"},
                new Person {Id = 9889, Name = "gsf_zero4"},
                new Person {Id = 9889, Name = "gsf_zero5"},
                new Person {Id = 100, Name = "gsf_zero6"}
            };

            //
            // 順序付け演算子には、以下のものが存在する。
            //
            //   ・OrderBy
            //   ・OrderByDescending
            //   ・ThenBy
            //   ・ThenByDescending
            //
            // OrderByは昇順ソート、OrderByDescendingは降順ソートを行う。どちらも単一キーにてソートを行う。
            // 複合キーにて、ソート処理を行う場合は、OrderBy及びOrderByDescendingに続いて、ThenBy及びThenByDescendingを利用する。
            //
            // OrderBy及びOrderByDescendingメソッドは、他のLINQ標準演算子と戻り値が異なっており
            //   IOrderedEnumerable<T>
            // を返す。また、ThenBy及びThenByDescendingメソッドは、引数にIOrderedEnumerable<T>を渡す必要がある。
            // なので、必然的に、ThenByはOrderByの後で呼び出さないと利用出来ない。
            //
            // LINQの並び替え処理は、安定ソート(Stable Sort)である。
            // つまり、同じキーの要素がシーケンス内に複数存在した場合、並び替えた結果は元の順番を保持している。
            //

            //
            // IDで昇順ソート.
            //
            var sortByIdAsc = persons.OrderBy(aPerson => aPerson.Id);

            Output.WriteLine("================= IDで昇順ソート =================");
            Output.WriteLine(string.Join(Environment.NewLine, sortByIdAsc));

            //
            // IDで降順ソート.
            //
            var sortByIdDesc = persons.OrderByDescending(aPerson => aPerson.Id);

            Output.WriteLine("================= IDで降順ソート =================");
            Output.WriteLine(string.Join(Environment.NewLine, sortByIdDesc));

            //
            // 安定ソートの確認。
            //
            var sortByIdAscAndDesc = persons.OrderByDescending(aPerson => aPerson.Id).OrderBy(aPerson => aPerson.Id);

            Output.WriteLine("================= 安定ソートの確認 =================");
            Output.WriteLine(string.Join(Environment.NewLine, sortByIdAscAndDesc));
        }
Example #11
0
        // GET: Search
        public ActionResult SearchResult(int? page)
        {
            var searchCriteria = Session["SearchCriteria"] as string;
            if (searchCriteria == null)
                return RedirectToAction("Error404", "Home");
            var records = db.Models.Where(x => x.ModelNumber.Contains(searchCriteria) && x.Status == "Active").ToList();

            var searchList = new List<SearchResultViewModel>();
            foreach (var item in records)
            {
                var searchItem = new SearchResultViewModel()
                {
                    ModelId = item.ModelId,
                    ModelName = item.ModelNumber,
                    Price = item.Price,
                    ImageUrl = (from ph in db.Photos
                                join pm in db.PhotoModels on ph.PhotoId equals pm.PhotoId
                                join m in db.Models on pm.ModelId equals m.ModelId
                                where pm.ModelId == item.ModelId
                                select ph.ImageUrl).FirstOrDefault(),

                    DtCreated = item.DtCreated,
                    CategoryName = (from c in db.Categories
                                    join p in db.Products on c.CategoryId equals p.CategoryId
                                    join i in db.Items on p.ProductId equals i.ProductId
                                    join m in db.Models on i.ItemId equals m.ItemId
                                    where m.ItemId == item.ItemId
                                    select c.Description).FirstOrDefault(),

                    ProductName = (from c in db.Categories
                                   join p in db.Products on c.CategoryId equals p.CategoryId
                                   join i in db.Items on p.ProductId equals i.ProductId
                                   join m in db.Models on i.ItemId equals m.ItemId
                                   where m.ItemId == item.ItemId
                                   select p.Description).FirstOrDefault(),

                    ItemName = (from c in db.Categories
                                join p in db.Products on c.CategoryId equals p.CategoryId
                                join i in db.Items on p.ProductId equals i.ProductId
                                join m in db.Models on i.ItemId equals m.ItemId
                                where m.ItemId == item.ItemId
                                select i.Description).FirstOrDefault()
                };
                searchList.Add(searchItem);
            }
            int count = records.Count();
            ViewBag.Count = count;
            ViewBag.Model = searchCriteria.ToString();
            Session.Remove("SearchCriteria");

            var pageNumber = page ?? 1;
            var pageOfProducts = searchList.OrderByDescending(s => s.DtCreated).ToPagedList(pageNumber, 10);
            ViewBag.pageOfProducts = pageOfProducts;

            return View(searchList.OrderByDescending(s => s.DtCreated));
        }
        private List<Photon> findNearestNeighbours(int number, Vector3 point, List<Photon> currentBest, int depth)
        {
            //If we are not a leaf node and we don't have any current bests, recurse down the tree 
            if (currentBest.Count == 0 && !isLeaf())
            {
                if (getComponentFromDepth(point, depth) < getComponentFromDepth(p.position, depth))
                {
                    currentBest = left.findNearestNeighbours(number, point, currentBest, depth + 1);
                }
                else if (right != null)
                {
                    currentBest = right.findNearestNeighbours(number, point, currentBest, depth + 1);
                }
            }

            //If there aren't enough points yet, add this one and return
            if (currentBest.Count < number)
            {
                currentBest.Add(p);
            }
            //Else see if any of the points are farther
            else
            {
                currentBest.OrderByDescending(x => (x.position - point).LengthSquared);
                //If so, remove the farthest, add this one, and return
                if ((currentBest[0].position - point).LengthSquared > (p.position - point).LengthSquared)
                {
                    currentBest.RemoveAt(0);
                    currentBest.Add(p);
                }
            }

            //If we are a leaf we are done
            //Otherwise we have to check to see if there might be points on the other side of the splitting
            //  plane which are closer than the current best, farthest point
            if (!isLeaf())
            {
                currentBest.OrderByDescending(x => (x.position - point).LengthSquared);
                float difference = getComponentFromDepth(point, depth) - getComponentFromDepth(p.position, depth);
                if ((currentBest[0].position - point).LengthSquared > difference * difference)
                {
                    if (difference < 0)
                    {
                        currentBest = left.findNearestNeighbours(number, point, currentBest, depth + 1);
                    }
                    else if (right != null)
                    {
                        currentBest = right.findNearestNeighbours(number, point, currentBest, depth + 1);
                    }
                }
            }

            return currentBest;
        }
        public void FillGrid()
        {
            TTSHWCFServiceClient client = new TTSHWCFServiceClient();

            List<Feasibility_Grid> gridData = new List<Feasibility_Grid>();

            gridData = client.Feasibility_FillGrid().ToList();

            try
            {
                string UserID = Convert.ToString(Session["UserID"]).ToUpper();
                Project_DataOwner[] oDOList = client.GetProjectsByDO("FEASIBILITY", UserID);
                DataOwner_Entity[] oDataOwner = client.GetAllDataOwner("TAdmin");

                var AdminArray = (from s in oDataOwner
                                  select s.GUID).ToList();

                bool IsAdmin = AdminArray.Contains(UserID);

                if (IsAdmin == false)
                {
                    List<Feasibility_Grid> oNewGrid = new List<Feasibility_Grid>();
                    if (gridData != null && gridData.Count() > 0 && oDOList != null && oDOList.Count() > 0)
                    {
                        var v = gridData.Select(z => z.Feasibility_Status_Name).Distinct().ToList();
                        oNewGrid = gridData.Where(z => z.Feasibility_Status_Name.ToUpper() == "NEW").Where(z => oDOList.Any(x => x.s_DisplayProject_ID == z.s_Display_Project_ID)).ToList();
                        oNewGrid.ForEach(i => i.Status = "New");
                        gridData.RemoveAll(z => z.Feasibility_Status_Name.ToUpper() == "NEW");
                        gridData.AddRange(oNewGrid);
                        gridData.Where(z => z.Feasibility_Status_Name.ToUpper() != "NEW").Where(z => oDOList.Any(x => x.s_DisplayProject_ID.ToUpper().Trim() != z.s_Display_Project_ID.ToUpper().Trim())).ToList().ForEach(i => i.Status = "View");
                        gridData.Where(z => z.Feasibility_Status_Name.ToUpper() != "NEW").Where(z => oDOList.Any(x => x.s_DisplayProject_ID.ToUpper().Trim() == z.s_Display_Project_ID.ToUpper().Trim())).ToList().ForEach(i => i.Status = "Edit");
                        gridData = gridData.OrderByDescending(z => z.i_Project_ID).ToList();
                    }
                }
                else
                {
                    gridData.Where(z => z.Feasibility_Status_Name.ToUpper() == "NEW").ToList().ForEach(i => i.Status = "New");
                    //gridData.Where(z => z.Feasibility_Status_Name.ToUpper() != "NEW").ToList().ForEach(i => i.Status = "View");
                    gridData.Where(z => z.Feasibility_Status_Name.ToUpper() != "NEW").ToList().ForEach(i => i.Status = "Edit");
                    gridData = gridData.OrderByDescending(z => z.i_Project_ID).ToList();
                }
            }
            catch (Exception ex1)
            {

            }

            rptrProjectDetail.DataSource = gridData;

            rptrProjectDetail.DataBind();
        }
Example #14
0
        public ActionResult Index(string sortOrder, int page=1)
        {
            PageInfo pageInfo = new PageInfo(PageConstants.itemsPerPage, page);
            NewsIndexModelView nivm = new NewsIndexModelView();
            nivm.PageInfo = pageInfo;



            List<News> sortedNews = new List<News>();
            if (User.IsInRole(Constants.UserRoles.AdminRoleName))
            {
                sortedNews = newsManagement.news.ToList<News>();
            }
            else
            {
                foreach (var item in newsManagement.news)
                {
                    if (item.IsVisible || User.Identity.Name == item.AuthorsID)
                    {
                        sortedNews.Add(item);
                    }
                }
            }
            switch (sortOrder)
            {
                case "name_desc":
                    sortedNews = sortedNews.OrderByDescending(s => s.AuthorsID).ToList();
                    break;
                case "Date":
                    sortedNews = sortedNews.OrderBy(s => s.Date).ToList();
                    break;
                case "date_desc":
                    sortedNews = sortedNews.OrderByDescending(s => s.Date).ToList();
                    break;
                default:
                    sortedNews = sortedNews.OrderBy(s => s.AuthorsID).ToList();
                    break;
            }

            ArticleSorting sortingParam = new ArticleSorting();

            sortingParam.CurrentSort = sortOrder;
            sortingParam.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            sortingParam.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

            nivm.ArticleSort = sortingParam;
            nivm.News = sortedNews.Skip((page - 1) * PageConstants.itemsPerPage).Take(PageConstants.itemsPerPage).ToList<News>(); ;
            nivm.PageInfo.TotalItems = sortedNews.Count;

            return View(nivm);
        }
        //удаление заданного кол-ва сетей по возрастанию
        public static List<Subnet> dropBadSubnets(List<Subnet> subnets, int count)
        {
            //сортировка по убыванию
            subnets = subnets.OrderByDescending(net => net.ID).ToList();
            subnets = subnets.OrderByDescending(net => net.quality).ToList();

            for (int i = 0; i < count; i++)
            {
                //удаление худших с конца
                subnets.RemoveAt(subnets.Count - 1);
            }

            return subnets;
        }
Example #16
0
        /// <summary>
        /// Returns list of packages from online gallery for a single page
        /// </summary>
        /// <param name="pkgType">Theme, Widget or Extension</param>
        /// <param name="page">Current page</param>
        /// <param name="sortOrder">Order - newest, most downloaded etc.</param>
        /// <param name="searchVal">Search term if it is search request</param>
        /// <returns>List of packages</returns>
        public static List<JsonPackage> FromGallery(string pkgType, int page = 0, Gallery.OrderType sortOrder = Gallery.OrderType.Newest, string searchVal = "")
        {
            var packages = new List<JsonPackage>();
            var gallery = CachedPackages.Where(p => p.Location == "G" || p.Location == "I");

            if (pkgType != "all")
                gallery = gallery.Where(p => p.PackageType == pkgType).ToList();

            foreach (var pkg in gallery)
            {
                if (string.IsNullOrEmpty(searchVal))
                {
                    packages.Add(pkg);
                }
                else
                {
                    if (pkg.Title.IndexOf(searchVal, StringComparison.OrdinalIgnoreCase) != -1
                        || pkg.Description.IndexOf(searchVal, StringComparison.OrdinalIgnoreCase) != -1
                        ||
                        (!string.IsNullOrWhiteSpace(pkg.Tags) &&
                         pkg.Tags.IndexOf(searchVal, StringComparison.OrdinalIgnoreCase) != -1))
                    {
                        packages.Add(pkg);
                    }
                }
            }

            Gallery.GalleryPager = new Pager(page, packages.Count, pkgType);

            if (packages.Count > 0)
            {
                switch (sortOrder)
                {
                    case Gallery.OrderType.Downloads:
                        packages = packages.OrderByDescending(p => p.DownloadCount).ThenBy(p => p.Title).ToList();
                        break;
                    case Gallery.OrderType.Rating:
                        packages = packages.OrderByDescending(p => p.Rating).ThenBy(p => p.Title).ToList();
                        break;
                    case Gallery.OrderType.Newest:
                        packages = packages.OrderByDescending(p => Convert.ToDateTime(p.LastUpdated, Utils.GetDefaultCulture())).ThenBy(p => p.Title).ToList();
                        break;
                    case Gallery.OrderType.Alphanumeric:
                        packages = packages.OrderBy(p => p.Title).ToList();
                        break;
                }
            }
            return packages.Skip(page * Constants.PageSize).Take(Constants.PageSize).ToList();
        }
        public JsonResult GetDeploymentPeriodDashboard(string sidx, string sord, int page, int rows)
        {
            List<ACM.Model.DeploymentPeriod> deploymentperiod = new List<ACM.Model.DeploymentPeriod>();
            //string loginId = Utility.LoginId(User.Identity.Name);

            DeploymentPeriodBO deploymentPeriodbo = new DeploymentPeriodBO();
            deploymentperiod = deploymentPeriodbo.GetAllDeploymentPeriods();
            switch (sidx.Trim())
            {
                case "DeploymentStartDate":
                    deploymentperiod = (sord == "asc") ? deploymentperiod.OrderBy(i => i.DeploymentStartDate).ToList() : deploymentperiod.OrderByDescending(i => i.DeploymentStartDate).ToList();
                    break;
                case "DeploymentEndEndDate":
                    deploymentperiod = (sord == "asc") ? deploymentperiod.OrderBy(i => i.DeploymentEndEndDate).ToList() : deploymentperiod.OrderByDescending(i => i.DeploymentEndEndDate).ToList();
                    break;

                case "DeploymentName":
                    deploymentperiod = (sord == "asc") ? deploymentperiod.OrderBy(i => i.DeploymentName).ToList() : deploymentperiod.OrderByDescending(i => i.DeploymentName).ToList();
                    break;

                case "Status":
                    deploymentperiod = (sord == "asc") ? deploymentperiod.OrderBy(i => i.Status).ToList() : deploymentperiod.OrderByDescending(i => i.Status).ToList();
                    break;
                //case "CampaignName":
                //    deploymentperiod = (sord == "asc") ? deploymentperiod.OrderBy(i => i.CampaignName).ToList() : deploymentperiod.OrderByDescending(i => i.CampaignName).ToList();
                //    break;
            }

            var totalRecords = deploymentperiod.Count();
            var assets = from a in deploymentperiod
                         select new
                         {
                             DeploymentPeriodId = a.DeploymentPeriodId,
                             DeploymentName = a.DeploymentName,
                             DeploymentStartDate =  a.DeploymentStartDate.ToShortDateString() ,
                             DeploymentEndEndDate=a.DeploymentEndEndDate.ToShortDateString() ,
                             Status = a.Status ,
                             Action="Edit"
                         };
            var result = new
            {
                total = (totalRecords + rows - 1) / rows, //number of pages
                page = page, //current page
                records = totalRecords, //total items
                rows = assets.AsEnumerable().Skip((page - 1) * rows).Take(rows)
            };

            return Json(result, JsonRequestBehavior.AllowGet);
        }
Example #18
0
        public Returns Go(Course course, List<Player> players)
        {
            PrintPlayer(players);

            CalculatePlayerPoints(course, players);

            Returns ret = new Returns();

            ret.standsStrokeplayNetto = players.OrderBy(x => x.FinalScoreStrokePlaynetto).ToArray();
            ret.standsStrokeplayBrutto = players.OrderBy(x => x.FinalScoreStrokePlayBrutto).ToArray();
            ret.standsStablefordNetto = players.OrderByDescending(x => x.finalScoreStableFordNetto).ToArray();
            ret.standsStablefordBrutto = players.OrderByDescending(x => x.finalScoreStableFordBrutto).ToArray();

            return ret;
        }
        public RespuestaBusquedaSolicitudesVob BuscarSolicitudes(SolicitudBusquedaSolicitudesVob solicitud)
        {
            List<SolicitudVob> lista = new List<SolicitudVob>();
            var solicitudrepositorio = new GNTSolicitudRepositorio();

            lista = solicitudrepositorio.BuscarSolicitudes();

            
            if (solicitud.SolicitudFilter.Codigo_Solicitud != null)
            {
                if (solicitud.SolicitudFilter.Codigo_Solicitud > 0)
                {
                    lista = lista.Where(x => x.Codigo_Solicitud == solicitud.SolicitudFilter.Codigo_Solicitud).ToList();
                }
            }

  
            if (solicitud.SolicitudFilter.FechaInicio != null && solicitud.SolicitudFilter.FechaFin != null)
            {
                lista = lista.Where(x => x.FechaSolicitud >= solicitud.SolicitudFilter.FechaInicio && x.FechaSolicitud <= solicitud.SolicitudFilter.FechaFin).ToList();
            }

            lista = lista.OrderByDescending(x => x.FechaSolicitud).ToList();

            int total = lista.Count();

            return new RespuestaBusquedaSolicitudesVob
            {
                listasolicitudes = lista.ToList(),
                totalelementos = total
            };

        }
        /// <summary>
        /// Returns the highest version of LocalDB installed, or null if none was found.
        /// </summary>
        /// <remarks>
        /// If one version is found, then that version is always returned.
        /// If multiple versions are found, then an attempt to treat those versions as decimal numbers is
        /// made and the highest of these is returned.
        /// </remarks>
        public virtual string TryGetLocalDBVersionInstalled()
        {
            var key = OpenLocalDBInstalledVersions(useWow6432Node: false);

            if (key.SubKeyCount == 0)
            {
                key = OpenLocalDBInstalledVersions(useWow6432Node: true);
            }

            if (key.SubKeyCount == 1)
            {
                return key.GetSubKeyNames()[0];
            }

            var orderableVersions = new List<Tuple<decimal, string>>();
            foreach (var subKey in key.GetSubKeyNames())
            {
                decimal decimalVersion;
                if (Decimal.TryParse(subKey, out decimalVersion))
                {
                    orderableVersions.Add(Tuple.Create(decimalVersion, subKey));
                }
            }

            return orderableVersions.OrderByDescending(v => v.Item1).Select(v => v.Item2).FirstOrDefault();
        }
Example #21
0
        public static void DoTestDescending()
        {
            List<int> numbers = new List<int> { 23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25 };
            numbers.CombSortDescending(Comparer<int>.Default);

            Debug.Assert(numbers.SequenceEqual(numbers.OrderByDescending(i => i)), "Wrong CombSort descending");
        }
        public ActionResult Index(EnginesModel model)
        {
            model = model ?? new EnginesModel();

            if (!string.IsNullOrEmpty(model.UploadName) && model.upload != null)
            {
                model.Message = UploadEngine(model.UploadName, model.UploadPlatforms);
            }

            var defaultPlatform = EnginePlatforms[0];

            var winBasePath = Path.Combine(Server.MapPath("~"), "engine", defaultPlatform);
            if (!Directory.Exists(winBasePath)) Directory.CreateDirectory(winBasePath);

            var items = new List<EngineItem>();
            foreach (var name in new DirectoryInfo(winBasePath).GetFiles().Select(x => x.Name).Select(Path.GetFileNameWithoutExtension))
            {
                var item = new EngineItem() { Name = name, Platforms = new List<string>() { defaultPlatform }, IsDefault = name == MiscVar.DefaultEngine};

                foreach (var p in EnginePlatforms.Where(x => x != defaultPlatform))
                {
                    if (System.IO.File.Exists(Path.Combine(Server.MapPath("~"), "engine", p, $"{name}.zip"))) item.Platforms.Add(p);
                }
                items.Add(item);
            }

            if (model.SearchName != null) items = items.Where(x => x.Name.Contains(model.SearchName)).ToList();

            model.Data = items.OrderByDescending(x => x.Name).AsQueryable();

            return View("EnginesIndex", model);
        }
Example #23
0
        public Search(Query query)
        {
            Query = query;
            ResultList = new List<QrelLine>();
            Connector conn = new Connector();

            List<Paragraph> paragraphs = conn.GetParagraph(query.Terms.Values.ToList());

            foreach (Paragraph paragraph in paragraphs)
            {
                String path = paragraph.Parent.Path;
                String xpath = paragraph.Xpath;
                Double relevance = paragraph.Relevance;

                ResultList.Add(new QrelLine(path, xpath, relevance));

            }

            ResultList = ResultList.OrderByDescending(v => v.Relevance).ToList();

            StringBuilder result = new StringBuilder();
            foreach (QrelLine qrelLine in ResultList)
            {
                String path = qrelLine.DocPath;
                String xpath = qrelLine.XmlPath;
                Double relevance = qrelLine.Relevance;

                result.AppendLine("[" + relevance + "] " + path + " - " + xpath);
            }
            Result = result.ToString();
        }
        public static List<FNOceanicResource> getOceanicCompositionForBody(int refBody)
        {
            List<FNOceanicResource> bodyOceanicComposition = new List<FNOceanicResource>();
            try {
                if (body_oceanic_resource_list.ContainsKey(refBody)) {
                    return body_oceanic_resource_list[refBody];
                } else {
                    ConfigNode[] bodyOceanicResourceList = GameDatabase.Instance.GetConfigNodes("OCEANIC_RESOURCE_DEFINITION").Where(res => res.GetValue("celestialBodyName") == FlightGlobals.Bodies[refBody].name).ToArray();
                    foreach (ConfigNode bodyOceanicConfig in bodyOceanicResourceList) {
                        string resourcename = null;
                        if (bodyOceanicConfig.HasValue("resourceName")) {
                            resourcename = bodyOceanicConfig.GetValue("resourceName");
                        }
                        double resourceabundance = double.Parse(bodyOceanicConfig.GetValue("abundance"));
                        string displayname = bodyOceanicConfig.GetValue("guiName");
                        FNOceanicResource bodyOceanicResource = new FNOceanicResource(resourcename, resourceabundance, displayname);
                        bodyOceanicComposition.Add(bodyOceanicResource);
                    }
                    if (bodyOceanicComposition.Count > 1) {
                        bodyOceanicComposition = bodyOceanicComposition.OrderByDescending(bacd => bacd.getResourceAbundance()).ToList();
                    }
                }
            } catch (Exception ex) {

            }
            return bodyOceanicComposition;
        }
        public IQueryable<ScoreInfoDataModel> Top()
        {
            var scores = new List<ScoreInfoDataModel>();
            var users = this.Data.Users
                            .All()
                            .Select(u => new
                            {
                                Id = u.Id,
                                Username = u.UserName
                            })
                            .ToList();

            foreach (var user in users)
            {
                var wins = this.Data.Scores.All().Count(s => s.PlayerId.ToString() == user.Id && s.ScoreStatus == ScoreStatus.Win);
                var losses = this.Data.Scores.All().Count(s => s.PlayerId.ToString() == user.Id && s.ScoreStatus == ScoreStatus.Loss);
                var draws = this.Data.Scores.All().Count(s => s.PlayerId.ToString() == user.Id && s.ScoreStatus == ScoreStatus.Draw);
                scores.Add(new ScoreInfoDataModel()
                {
                    Wins = wins,
                    Losses = losses,
                    Draws = draws,
                    Username = user.Username,
                    Points = 100 * wins + 30 * draws + 15 * losses
                });
            }

            return scores.OrderByDescending(s => s.Points).ThenBy(s => s.Wins).Take(10).AsQueryable();
        }
        public override void Application_Starting()
        {
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new PlugViewEngine());

            ModelBinders.Binders.Add(typeof(WidgetBase), new WidgetBinder());

            var routes = new List<RouteDescriptor>();
            Type plugBaseType = typeof(PluginBase);

            BuildManager.GetReferencedAssemblies().Cast<Assembly>().Each(m => m.GetTypes().Each(p =>
            {
                if (plugBaseType.IsAssignableFrom(p) && !p.IsAbstract && !p.IsInterface)
                {
                    var plug = Activator.CreateInstance(p) as PluginBase;
                    if (plug != null)
                    {
                        routes.AddRange(plug.RegistRoute());
                        plug.InitScript();
                        plug.InitStyle();
                    }
                }
            }));
            RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.OrderByDescending(m => m.Priority).Each(m => RouteTable.Routes.MapRoute(m.RouteName, m.Url, m.Defaults, m.Constraints, m.Namespaces));
            ContainerAdapter.RegisterType<IUserService, UserService>();
            ContainerAdapter.RegisterType<IDataDictionaryService, DataDictionaryService>();
            ContainerAdapter.RegisterType<ILanguageService, LanguageService>();

            DisplayViewSupport.SupportMobileView();
            DisplayViewSupport.SupportIEView();
        }
    static void Main()
    {
        int jobsCount = int.Parse(Console.ReadLine());
        Dictionary<string, int> jobs = new Dictionary<string, int>();

        for (int i = 0; i < jobsCount; i++)
        {
            string[] tokens = Console.ReadLine().Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
            string job = tokens[0].Trim();

            if (!jobs.ContainsKey(job)) jobs.Add(job, int.Parse(tokens[1]));
        }

        int employeesCount = int.Parse(Console.ReadLine());
        List<Employee> employees = new List<Employee>();

        for (int i = 0; i < employeesCount; i++)
        {
            string[] tokens = Console.ReadLine().Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
            string[] names = tokens[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            employees.Add(new Employee(names[0], names[1], jobs[tokens[1].Trim()]));
        }

        employees = employees.OrderByDescending(x => x.rate).ThenBy(x => x.secondName).ThenBy(x => x.firstName).ToList();

        foreach (var item in employees) Console.WriteLine("{0} {1}", item.firstName, item.secondName);
    }
Example #28
0
    static void Main(string[] args)
    {
        Component motherBoard1 = new Component("AsusP8H67/H67/1155", "Game Station", (decimal)155.00);
        Component graphicCard1 = new Component("ATI Radeon HD7850", (decimal)229.00);
        Component ram1 = new Component("2x4GB DDR3 1600Mhz", (decimal)129.00);
        Computer pc1 = new Computer("Asus Game Machine", new List<Component> { motherBoard1, graphicCard1, ram1 });
        Console.WriteLine(pc1);
        Console.WriteLine();
        Console.WriteLine("----------------------------------------------------------------");
        Component motherBoard2 = new Component("ASUS P8H61-M LX2/SI/LGA1155", "Home Station", (decimal)98.00);
        Component graphicCard2 = new Component("ATI Radeon HD 7750", (decimal)138.00);
        Component ram2 = new Component("4 GB DDR3 1333 MHz", (decimal)65.00);
        Computer pc2 = new Computer("Home Machine", new List<Component> { motherBoard2, graphicCard2, ram2 });
        Console.WriteLine(pc2);
        Console.WriteLine();
        Console.WriteLine("----------------------------------------------------------------");
        Component motherBoard3 = new Component("ASROCK Z87 PRO4 BULK", "Game Station", (decimal)217.00);
        Component graphicCard3 = new Component("SAPPHIRE R9 270 2G GDDR5 OC", (decimal)358.00);
        Component ram3 = new Component("2x4GB DDR3 1600 MHz", (decimal)148.00);
        Computer pc3 = new Computer("Game Machine New", new List<Component> { motherBoard3, graphicCard3, ram3 });
        Console.WriteLine(pc3);
        Console.WriteLine();
        Console.WriteLine("----------------------------------------------------------------");
        Console.WriteLine("----------------------------------------------------------------");
        List<Computer> computers = new List<Computer>() { pc1, pc2, pc3 };
        computers.OrderByDescending(computer => computer.Price).ToList().ForEach(computer => Console.WriteLine(computer.ToString()));

    }
 public static void Run()
 {
     using (FastScanner fs = new FastScanner(new BufferedStream(Console.OpenStandardInput())))
     using (StreamWriter writer = new StreamWriter(new BufferedStream(Console.OpenStandardOutput())))
     {
         int n = fs.NextInt(), k = fs.NextInt(), q = fs.NextInt();
         User[] t = new User[n];
         List<User> d = new List<User>(k);
         for (int i = 0; i < n; i++)
         {
             t[i] = new User { Id = i, Val = fs.NextInt() };
         }
         while (q-- > 0)
         {
             int type = fs.NextInt(), id = fs.NextInt() - 1;
             if (type == 1)
             {
                 if (d.Count < k) d.Add(t[id]);
                 else
                 {
                     d = d.OrderByDescending(el => el.Val).ToList();
                     if (d.Last().Val < t[id].Val)
                     {
                         d.RemoveAt(k - 1);
                         d.Add(t[id]);
                     }
                 }
             }
             else
             {
                 writer.WriteLine(d.Contains(t[id]) ? "YES" : "NO");
             }
         }
     }
 }
Example #30
0
File: UPT.cs Project: am1guma/PSSC
 private void afiseazaStudentiCazati(object sender, EventArgs e)
 {
     int nr = Convert.ToInt32(textBox3.Text);
     double min = Convert.ToDouble(textBox4.Text);
     double max = Convert.ToDouble(textBox5.Text);
     List<FisaCazare> fise = new List<FisaCazare>();
     foreach (DataRowView drv in studentiBindingSource.List)
     {
         int suma = 0;
         int n = 0;
         foreach (DataRow dr in databaseDataSet.Tables[1].Rows)
             if (drv["Nr_matricol"].ToString().Equals(dr["Nr_matricol"].ToString()))
             {
                 suma += Convert.ToInt32(dr["Nota"].ToString());
                 n++;
             }
         FisaCazare fisa = new FisaCazare(drv["Nume"].ToString(), drv["Prenume"].ToString(), drv["Facultate"].ToString(), Convert.ToInt32(drv["An"].ToString()), Math.Round((double)suma / n,2));
         fise.Add(fisa);
     }
     List<FisaCazare> SortedList = fise.OrderByDescending(o => o.Medie).ToList().FindAll(c => (c.Medie<=max) && (c.Medie>=min));
     while (SortedList.Count > nr)
         SortedList.RemoveAt(SortedList.Count - 1);
     var bindingList = new BindingList<FisaCazare>(SortedList);
     var source = new BindingSource(bindingList, null);
     dataGridView1.DataSource = source;
 }