Esempio n. 1
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;
        }
Esempio n. 2
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();
                    }
                }
            }
        }
Esempio n. 3
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;
        }
Esempio n. 4
0
        //Query5:Получить следующую структуру (передать Id пользователя в параметры)
        //		User
        //		Последний пост пользователя(по дате)
        //		Количество комментов под последним постом
        //		Количество невыполненных тасков для пользователя
        //		Самый популярный пост пользователя(там где больше всего комментов с длиной текста больше 80 символов)
        //		Самый популярный пост пользователя(там где больше всего лайков)
        public static UserStruct Query5(int userId)
        {
            UserStruct user = new UserStruct();

            try
            {
                SomeEntity      usr   = GetEntities().Where(u => u.Id == userId).FirstOrDefault();
                List <FullPost> posts = usr?.Posts.ToList();

                user.LastPost = posts?.OrderByDescending(p => p.CreatedAt).FirstOrDefault();

                user.LastPostCommentsCount = posts?.OrderByDescending(p => p.CreatedAt).FirstOrDefault()?.Comments.Count() ?? 0;

                user.MostPopularByComms = posts?.Where(p => p.Comments.Count() > 0)
                                          .Select(a => new { CurrentPost = a, CommentsCount = a.Comments.Where(c => c.Body.Length > 80).Count() })
                                          .OrderByDescending(i => i.CommentsCount)
                                          .Where(i => i.CommentsCount > 0)
                                          .FirstOrDefault()?.CurrentPost;

                user.MostPopularByLikes = posts?.OrderByDescending(p => p.Likes).FirstOrDefault();

                user.UnCompletedTasksCount = usr.Todos.Where(t => t.IsComplete == false).Count();
            }
            catch (Exception ex)
            {
                Console.Clear();
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }

            return(user);
        }
Esempio n. 5
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();
        }
Esempio n. 6
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;
        }
Esempio n. 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));


            }

            
            
        }
Esempio n. 8
0
        public void AddComponent(BaseComponent.ComponentType type, Point?location)
        {
            _selectorMode = false;

            ClearComponent();

            _currentComponent = BaseComponent.Create(type, _canvas);

            _currentComponent.OnComponentActionCompleted = OnComponentActionCompleted;
            _currentComponent.OnComponentActionUpdated   = OnComponentActionUpdated;

            // now try and see what the last component of this type has for options and copy it over
            var lastComponent = FindLastComponent(type);

            _currentComponent.CopyOptions(lastComponent);
            _currentComponent.Color = ActiveColor;
            if (location != null)
            {
                _currentComponent.SetLocation((float)location.Value.X, (float)location.Value.Y);
            }

            var currrentHighestDisplayPriority = _components?.OrderByDescending(c => c.DisplayOrder).FirstOrDefault()?.DisplayOrder;

            _currentComponent.DisplayOrder = (currrentHighestDisplayPriority ?? 0) + 1;

            ComponentSelected?.Invoke();

            _canvas.Invalidate();
        }
        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;
        }
Esempio n. 10
0
        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;
        }
Esempio n. 12
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));
        }
Esempio n. 13
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));
        }
Esempio n. 14
0
        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;
        }
 private void SortListByResult()
 {
     SortResultDescending = !SortResultDescending;
     if (_sortResultDescending)
     {
         _localHistoryList = _localHistoryList?.OrderBy(x => x.SortingResult).ToList();
     }
     else
     {
         _localHistoryList = _localHistoryList?.OrderByDescending(x => x.SortingResult).ToList();
     }
     RefreshCollection(_howMuchToShow);
 }
        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();
        }
Esempio n. 17
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);
        }
Esempio n. 18
0
        //удаление заданного кол-ва сетей по возрастанию
        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;
        }
Esempio n. 19
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);
        }
Esempio n. 21
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;
        }
Esempio n. 22
0
        public static List <BuildingListViewModel> GetAllBuildingListViewModel(Guid customerGuid, EnRequestType type)
        {
            var list = new List <BuildingListViewModel>();

            try
            {
                using (var cn = new SqlConnection(Cache.ConnectionString))
                {
                    var cmd = new SqlCommand("sp_Buildings_GetBuildingListViewModel", cn)
                    {
                        CommandType = CommandType.StoredProcedure
                    };
                    cmd.Parameters.AddWithValue("@cusGuid", customerGuid);
                    cmd.Parameters.AddWithValue("@buType", (short)type);

                    cn.Open();
                    var dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        list.Add(LoadData(dr));
                    }
                    dr.Close();
                    cn.Close();
                }

                list = list?.OrderByDescending(q => q.CreateDate)?.Take(100).ToList();
            }
            catch (Exception ex)
            {
                WebErrorLog.ErrorInstence.StartErrorLog(ex);
            }
            return(list);
        }
Esempio n. 23
0
        public ActionResult ProcLog(string primaryKey)
        {
            List <PDP_PROC_LOG> list = _procLogService.GetManay(r => r.PROC_CAT_CODE == "3" && r.PROC_CONTENT_ID == primaryKey);

            if (list?.OrderByDescending(r => r.UPD_DATE).ToList().Count > 0)
            {
                var value = list?.OrderByDescending(r => r.UPD_DATE).ToList()[0];
                return(Content(new
                {
                    startDate = value.START_TIME == null ? null : DateTime.Parse(value.START_TIME.ToString()).ToString("yyyy-MM-dd"),
                    endDate = value.END_TIME == null ? null : DateTime.Parse(value.END_TIME.ToString()).ToString("yyyy-MM-dd"),
                    patientId = value.PATIENT_ID
                }.ToJson()));
            }
            return(Error());
        }
        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
            };

        }
        public static List <ProductGardeshViewModel> GetGardesh(Guid prdGuid)
        {
            var list = new List <ProductGardeshViewModel>();

            try
            {
                using (var cn = new SqlConnection(Cache.ConnectionString))
                {
                    var cmd = new SqlCommand("sp_Product_Gardesh", cn)
                    {
                        CommandType = CommandType.StoredProcedure
                    };
                    cmd.Parameters.AddWithValue("@prdGuid", prdGuid);
                    cn.Open();
                    var dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        list.Add(LoadData(dr));
                    }
                    dr.Close();
                    cn.Close();
                }
            }
            catch (Exception ex)
            {
                WebErrorLog.ErrorInstence.StartErrorLog(ex);
            }

            return(list?.OrderByDescending(q => q.DateM)?.ToList());
        }
Esempio n. 26
0
File: UPT.cs Progetto: 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;
 }
        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;
        }
Esempio n. 28
0
        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();
        }
Esempio n. 29
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 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);
        }
Esempio n. 31
0
        private async Task <DeploymentServiceListModel> GetListAsync()
        {
            var deployments = new List <DeploymentServiceModel>();
            var response    = await this.client.GetAllAsync(DeploymentsCollection);

            if (response != null && response.Items.Count > 0)
            {
                var result = response.Items.Select(this.CreateDeploymentServiceModel);

                foreach (var item in result)
                {
                    if (item.DeploymentMetrics == null)
                    {
                        item.DeploymentMetrics = new DeploymentMetricsServiceModel();
                    }

                    if (item.DeploymentMetrics.DeviceStatuses == null)
                    {
                        item.DeploymentMetrics.DeviceStatuses = await this.FetchDeviceStatuses(item.Id);
                    }

                    deployments.Add(item);
                }
            }

            return(new DeploymentServiceListModel(deployments?.OrderByDescending(x => x.CreatedDateTimeUtc).ToList()));
        }
    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);
    }
Esempio n. 33
0
        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();
        }
        /// <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();
        }
 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");
             }
         }
     }
 }
Esempio n. 36
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");
        }
Esempio n. 37
0
        /// <summary>
        /// Get company responses from Microsoft Azure Table storage.
        /// </summary>
        /// <param name="userId">Id of the user to fetch the responses submitted by him.</param>
        /// <returns>A task that represent collection to hold company responses data.</returns>
        public async Task <IEnumerable <CompanyResponseEntity> > GetUserCompanyResponseAsync(string userId)
        {
            await this.EnsureInitializedAsync();

            string partitionKeyCondition   = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, Constants.CompanyResponseEntityPartitionKey);
            string userIdCondition         = TableQuery.GenerateFilterCondition(UserId, QueryComparisons.Equal, userId);
            string combinedFilterCondition = TableQuery.CombineFilters(partitionKeyCondition, TableOperators.And, userIdCondition);

            TableQuery <CompanyResponseEntity> query             = new TableQuery <CompanyResponseEntity>().Where(combinedFilterCondition);
            TableContinuationToken             continuationToken = null;
            var userRequestCollection = new List <CompanyResponseEntity>();

            do
            {
                var queryResult = await this.ResponsesCloudTable.ExecuteQuerySegmentedAsync(query, continuationToken);

                if (queryResult?.Results != null)
                {
                    userRequestCollection.AddRange(queryResult.Results);
                    continuationToken = queryResult.ContinuationToken;
                }
            }while (continuationToken != null);

            return(userRequestCollection?.OrderByDescending(request => request.LastUpdatedDate));
        }
Esempio n. 38
0
 public void MarkUseds(List <uint> used)
 {
     // Remove those used
     _unusedValues.RemoveAll(x => used.Contains(x));
     // Update current value to top from outcome set
     _currVal = (uint)(_unusedValues?.OrderByDescending(t => t).FirstOrDefault() ?? 1);
 }
Esempio n. 39
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()));

    }
Esempio n. 40
0
 public SubCategoryResult CalculateTotalResult(List <ParticipantResult> participantResults)
 {
     return(new SubCategoryResult
     {
         Name = Name,
         OrderedParticipantResults = participantResults?.OrderByDescending(x => x.Value).ToList()
     });
 }
Esempio n. 41
0
        public async Task <int> GetRoundNumberByPlayerID(int playerID)
        {
            List <PlayerHistoryEntity> historyEntities = await base.DataSvc.PlayerHistoryRepo.GetAsync();

            int?lastRound = historyEntities?.OrderByDescending(history => history.RoundNumber)?.FirstOrDefault()?.RoundNumber;

            return(lastRound != null ? lastRound.Value + 1 : 1);
        }
Esempio n. 42
0
 /// <summary>
 ///     Orders the enemy minions.
 /// </summary>
 /// <param name="minions">The minions.</param>
 /// <returns></returns>
 private List <Obj_AI_Minion> OrderEnemyMinions(List <Obj_AI_Minion> minions)
 {
     return
         (minions?.OrderByDescending(minion => minion.GetMinionType().HasFlag(MinionTypes.Siege))
          .ThenBy(minion => minion.GetMinionType().HasFlag(MinionTypes.Super))
          .ThenBy(minion => minion.Health)
          .ThenByDescending(minion => minion.MaxHealth)
          .ToList());
 }
Esempio n. 43
0
        public string MatchSolution(string solutionPath)
        {
            var version = GetVisualStudioVersionNumber(solutionPath);

            var solutionMajorVersion = GetMajorVersion(version);

            var firstInstanceWithMatchingVersion = _visualStudioInstances?.OrderByDescending(v => v.Version).FirstOrDefault(vr => solutionMajorVersion == GetMajorVersion(vr.Version));

            //If there's a visual studio solution that matches the one used to create the solution:
            if (firstInstanceWithMatchingVersion != null)
            {
                return(firstInstanceWithMatchingVersion.VisualStudioMSBuildPath);
            }
            //If no version matches, return the max version
            else
            {
                return(_visualStudioInstances?.OrderByDescending(v => v.Version).FirstOrDefault().VisualStudioMSBuildPath);
            }
        }
 public IEnumerable <string> GetSupportedCaptureResolutions()
 {
     return(supportedImageFormats?.
            OrderByDescending(format => format.Width).
            ThenBy(format => format.Height).
            Select((imageFormat) =>
     {
         return $"{imageFormat.Width}*{imageFormat.Height}";
     }).Distinct() ?? new string[0]);
 }
Esempio n. 45
0
        public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
        {
            List <MethodInterceptionBaseAttribute> classAttributes =
                type?.GetCustomAttributes <MethodInterceptionBaseAttribute>(true).ToList();
            var methodAttributes = type?.GetMethod(method.Name)?.GetCustomAttributes <MethodInterceptionBaseAttribute>(true);

            classAttributes?.AddRange(methodAttributes);

            // ReSharper disable once CoVariantArrayConversion
            return(classAttributes?.OrderByDescending(x => x.Priority).ToArray());
        }
        PositiveDiagnosisState GetLatest()
        {
            var latest = PositiveDiagnoses?.OrderByDescending(p => p.DiagnosisDate)?.FirstOrDefault();

            if (latest == null)
            {
                latest = new PositiveDiagnosisState();
                PositiveDiagnoses.Add(latest);
            }

            return(latest);
        }
Esempio n. 47
0
        public List <DriverStoreEntry> EnumeratePackages()
        {
            List <DriverStoreEntry> driverStoreEntries = new List <DriverStoreEntry>();

            DismApi.Initialize(DismLogLevel.LogErrors);

            try
            {
                using (DismSession session = this.GetSession())
                {
                    List <DeviceDriverInfo> driverInfo = this.Type == DriverStoreType.Online
                        ? ConfigManager.GetDeviceDriverInfo()
                        : null;

                    foreach (var driverPackage in DismApi.GetDrivers(session, false))
                    {
                        DriverStoreEntry driverStoreEntry = new DriverStoreEntry
                        {
                            DriverClass          = driverPackage.ClassDescription,
                            DriverInfName        = Path.GetFileName(driverPackage.OriginalFileName),
                            DriverPublishedName  = driverPackage.PublishedName,
                            DriverPkgProvider    = driverPackage.ProviderName,
                            DriverSignerName     = driverPackage.DriverSignature == DismDriverSignature.Signed ? SetupAPI.GetDriverSignerInfo(driverPackage.OriginalFileName) : string.Empty,
                            DriverDate           = driverPackage.Date,
                            DriverVersion        = driverPackage.Version,
                            DriverFolderLocation = Path.GetDirectoryName(driverPackage.OriginalFileName),
                            DriverSize           = DriverStoreRepository.GetFolderSize(new DirectoryInfo(Path.GetDirectoryName(driverPackage.OriginalFileName))),
                            BootCritical         = driverPackage.BootCritical,
                            Inbox = driverPackage.InBox,
                        };

                        var deviceInfo = driverInfo?.OrderByDescending(d => d.IsPresent)?.FirstOrDefault(e =>
                                                                                                         string.Equals(Path.GetFileName(e.DriverInf), driverStoreEntry.DriverPublishedName, StringComparison.OrdinalIgnoreCase) &&
                                                                                                         e.DriverVersion == driverStoreEntry.DriverVersion &&
                                                                                                         e.DriverDate == driverStoreEntry.DriverDate);

                        driverStoreEntry.DeviceName    = deviceInfo?.DeviceName;
                        driverStoreEntry.DevicePresent = deviceInfo?.IsPresent;

                        driverStoreEntries.Add(driverStoreEntry);
                    }
                }
            }
            finally
            {
                DismApi.Shutdown();
            }

            return(driverStoreEntries);
        }
Esempio n. 48
0
 /// <summary>
 /// Méthode qui va regarder les cartes pour trouver s'il y a un RoyalFlush
 /// dans la main.
 /// </summary>
 /// <returns> True si un RoyalFlush present False si pas de RoyalFlush</returns>
 private bool RoyalFlush()
 {
     if (_straightList != null &&
         (int)_straightList[0].Value == 14 &&
         _flushList != null)
     {
         if (Enumerable.SequenceEqual(_straightList?.OrderByDescending(t => t),
                                      _flushList?.OrderByDescending(t => t)))
         {
             AddCardHandStrength(_straightList);
             return(true);
         }
     }
     return(false);
 }
Esempio n. 49
0
        private string ReplyWithLastRanCampaign()
        {
            PeopleStageSystemSummary firstSystem     = apiClient.GetPeopleStageSystems()?.FirstOrDefault();
            List <ElementStatus>     campaigns       = apiClient.GetPeopleStageCampaigns(firstSystem);
            ElementStatus            lastRanCampaign = campaigns?.OrderByDescending(c => c.LastRan)?.FirstOrDefault();

            if (lastRanCampaign?.LastRan == null)
            {
                return("I don't know - I don't have any campaign information");
            }
            else
            {
                return(lastRanCampaign.Description + " last ran " + FormatDateForReply("on", lastRanCampaign.LastRan.Value));
            }
        }
        protected override Task <string[]> FindAutoCompleteList(string value)
        {
            return(Task.Run(() =>
            {
                value = value.ToLower();
                // находим узел, который начинается с value
                var rootSubTree = TreeHelper.FindParentForNode(new Node(value), _tree.Root);

                // Если корень поддерева совпадает с корнем дерева
                // значит значение не найдено в словаре
                if (rootSubTree == _tree.Root)
                {
                    return new string[] { }
                }
                ;

                // Если корень поддерева не начинается с введенного слова
                // и не один из детей не начинается с введенного слова
                // значит не найдено слово в словаре
                if (rootSubTree.Word != null && !rootSubTree.Word.StartsWith(value) &&
                    !rootSubTree.Child.Any(x => x.Word.StartsWith(value)))
                {
                    return new string[] { }
                }
                ;

                var startWith = new List <Node>();

                // Если корень поддерева начинается с value, то его тоже вносим в список
                if (rootSubTree.Word != null && rootSubTree.Word.StartsWith(value))
                {
                    startWith.Add(rootSubTree);
                }

                // собираем все дочерние узлы в кучу
                startWith.AddRange(TreeHelper.GetAllChildNodes(rootSubTree));

                return startWith?
                .OrderByDescending(b => b.Index)
                .Take(10)
                .Select(a => a.Word)
                .ToArray();
            }));
        }
Esempio n. 51
0
        public static string[] GetErrorMessages(this Exception ex)
        {
            var errors = new List <string>();

            var error = ex;

            for (; ;)
            {
                if (error == null)
                {
                    break;
                }

                errors.Add(error.Message);
                error = error.InnerException;
            }

            return(errors?.OrderByDescending(p => p)?.ToArray());
        }
Esempio n. 52
0
        protected List <CategoryFacetValuesTreeNode> GetTreeNodes(FacetSetting facetSetting, IList <Facet> facets, SelectedFacets selectedFacets,
                                                                  TreeNode <Overture.ServiceModel.Products.Category> categoryTree, CultureInfo culture, CategoryFacetCounts counts)
        {
            var categoryChildren       = categoryTree.Children;
            var categoryChildrenLookup = categoryChildren.ToLookup(_ => _.Value.DisplayName.GetLocalizedValue(culture.Name));
            var facet = facets.FirstOrDefault(f => f.FieldName == facetSetting.FieldName);
            var countsForFacetValues = counts?.Facets?.FirstOrDefault(fc => facetSetting.FieldName.StartsWith(fc.FieldName))?.FacetValues;

            List <CategoryFacetValuesTreeNode> nodes = null;

            var facetValues = facet?.FacetValues.Concat(facet.OnDemandFacetValues);

            if (facetValues != null)
            {
                nodes = (from fv in facetValues
                         let category = categoryChildrenLookup[fv.Value].FirstOrDefault()
                                        where category != null
                                        let totalCount = countsForFacetValues?.FirstOrDefault(fcv => fcv.Value.Equals(category.Value.Id, StringComparison.OrdinalIgnoreCase))?.Quantity
                                                         select new CategoryFacetValuesTreeNode(fv.Title, fv.Value, totalCount != null ? totalCount.Value : fv.Quantity, facetSetting.FacetType, facetSetting.FieldName, fv.IsSelected, fv.IsRemovable)
                {
                    CategoryId = category.Value.Id
                }).ToList();
            }

            if (nodes == null || nodes.Count == 0)
            {
                var selected = selectedFacets.Facets.Where(f => f.FieldName == facetSetting.FieldName);
                if (selected != null && selected.Count() > 0)
                {
                    nodes = (from fv in selected
                             let category = categoryChildrenLookup[fv.Value].FirstOrDefault()
                                            where category != null
                                            let totalCount = countsForFacetValues?.FirstOrDefault(fcv => fcv.Value.Equals(category.Value.Id, StringComparison.OrdinalIgnoreCase))?.Quantity
                                                             select new CategoryFacetValuesTreeNode(fv.DisplayName, fv.Value, totalCount != null ? totalCount.Value : 0, facetSetting.FacetType, facetSetting.FieldName, true, fv.IsRemovable)
                    {
                        CategoryId = category.Value.Id
                    }).ToList();
                }
            }

            return(nodes?.OrderByDescending(n => n.Quantity).ToList());
        }
Esempio n. 53
0
        public static HistoricoCoberturaContratada ObterHistorico(CoberturaContratada coberturaContratada,
                                                                  List <IBeneficiario> beneficiarios, Periodicidade?periodicidade,
                                                                  decimal valorBeneficio, decimal valorCapital, decimal valorContribuicao, DateTime dataImplantacao)
        {
            var beneficiarioMaisNovo = beneficiarios?.OrderByDescending(x => x.DataNascimento).FirstOrDefault();

            var dto = new HistoricoCoberturaContratada(coberturaContratada)
            {
                SexoBeneficiario           = beneficiarioMaisNovo?.Sexo,
                DataNascimentoBeneficiario = beneficiarioMaisNovo?.DataNascimento,
                PeriodicidadeId            = (int)periodicidade.GetValueOrDefault(),
                ValorBeneficio             = valorBeneficio,
                ValorCapital      = valorCapital,
                ValorContribuicao = valorContribuicao
            };

            dto.InformaStatus(StatusCobertura.StatusCoberturaEnum.Activa, dataImplantacao);

            return(dto);
        }
Esempio n. 54
0
        public IEnumerable <ErrorData> GetValues(string pattern)
        {
            var values = new List <ErrorData>();

            if (!IsConnected)
            {
                TryToConnect();
            }

            if (!IsConnected)
            {
                return(values);
            }

            var server = _connectionMultiplexer.GetServer(_connectionString);
            var keys   = server.Keys(pattern: pattern);

            values.AddRange(keys.Select(key => GetData(key)));
            return(values?.OrderByDescending(item => item.Timestamp).ToList());
        }
Esempio n. 55
0
        /// <summary>
        /// 按条件获取数据列表 条件字典Key可以取固定值 selectfields orderby 框架将自动处理
        /// </summary>
        /// <param name="dicwhere">查询条件 字段名可以增加|b |s |l 等作为搜索条件</param>
        /// <returns>List&lt;Comment&gt;.</returns>
        public static List <CommentView> GetList(Dictionary <string, object> dicwhere)
        {
            var res = new List <CommentView>();

            if (dicwhere.Keys.Contains(nameof(Comment.IsDeleted)))
            {
                dicwhere[nameof(Comment.IsDeleted)] = 0;
            }
            else
            {
                dicwhere.Add(nameof(Comment.IsDeleted), 0);
            }
            var list = CommentRepository.Instance.GetList <Comment>(dicwhere).ToList();

            if (list != null && list.Count > 0)
            {
                var sessionids = list.GroupBy(x => x.Commentid).Select(x => x.Key).Distinct().ToList();
                sessionids.ForEach((item) =>
                {
                    var sessionList = list.Where(x => x.Commentid == item)?.OrderByDescending(x => x.CreateTime)?.ToList();
                    var mainSession = sessionList.Last();
                    var replys      = sessionList.Where(x => x.KID != mainSession.KID)?.ToList() ?? null;
                    res.Add(new CommentView()
                    {
                        KID        = mainSession.KID,
                        CreateTime = mainSession.CreateTime,
                        Memberid   = mainSession.Memberid,
                        MemberName = mainSession.MemberName,
                        BlogNum    = mainSession.BlogNum,
                        Commentid  = mainSession.Commentid,
                        ToMemberid = mainSession.ToMemberid,
                        Content    = mainSession.Content,
                        Avatar     = mainSession.Avatar,
                        Replys     = replys
                    });
                });
            }

            return(res?.OrderByDescending(x => x.CreateTime)?.ToList());
        }
Esempio n. 56
0
        public static HistoricoCoberturaContratada ObterHistorico(CoberturaContratada coberturaContratada,
                                                                  List <IBeneficiario> beneficiarios, Periodicidade?periodicidade,
                                                                  decimal valorBeneficio, decimal valorCapital, decimal valorContribuicao)
        {
            var dto = new HistoricoCoberturaContratada(coberturaContratada);

            var beneficiarioMaisNovo = beneficiarios?.OrderByDescending(x => x.DataNascimento).FirstOrDefault();

            dto.SexoBeneficiario           = beneficiarioMaisNovo?.Sexo;
            dto.DataNascimentoBeneficiario = beneficiarioMaisNovo?.DataNascimento;

            if (periodicidade != null)
            {
                dto.PeriodicidadeId = (int)periodicidade;
            }

            dto.ValorBeneficio    = valorBeneficio;
            dto.ValorCapital      = valorCapital;
            dto.ValorContribuicao = valorContribuicao;

            return(dto);
        }
Esempio n. 57
0
        public JsonResponse GetListBlogTypes([FromBody] PrenextModel model)
        {
            try
            {
                var dic = new Dictionary <string, object>
                {
                    { nameof(Category.IsDeleted), 0 },
                    { nameof(Category.States), 0 }
                };
                string          key      = ConfigUtil.BlogTypeListCacheKey;
                List <Category> retlist  = new List <Category>();
                var             cacheobj = CacheHelper.GetCacheItem(key)?.ToString() ?? "";
                if (!string.IsNullOrEmpty(cacheobj))
                {
                    retlist = CacheHelper.GetCacheItem(key)?.DeserialObjectToList <Category>();
                }
                if (retlist == null || retlist.Count == 0)
                {
                    retlist = BlogHelper.GetList_Category(dic);
                    CacheHelper.AddCacheItem(key, retlist.SerializObject(), DateTime.Now.AddDays(2), Cache.NoSlidingExpiration, CacheItemPriority.High);
                }

                retlist = retlist?.OrderByDescending(x => x.CreateTime)?.OrderByDescending(x => x.Sort)?.ToList();

                return(new JsonResponse {
                    Code = retlist != null ? 0 : 1, Data = retlist
                });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex, "BlogController/GetListBlogTypes");
                return(new JsonResponse {
                    Code = 1, Msg = "程序好像开小差了" + ex.Message
                });
            }
        }
        private string GetInnerBodyMessageForAccountlevel(List <ProjectedLog> logs)
        {
            var orderedLog = logs?.OrderByDescending(x => x.Created)?.ToList() ?? null;

            string logdetails = null;

            if (orderedLog == null)
            {
                return(null);
            }

            foreach (var log in orderedLog)
            {
                string batchId   = null;
                string dispachId = null;
                if (!string.IsNullOrEmpty(log.BatchId))
                {
                    batchId = $"BatchId : {log.BatchId}";
                }

                logdetails += $"{log.Created.ToString()}   {batchId} {log.Message} \n";
            }
            return(logdetails);
        }
Esempio n. 59
0
        public ActionResult Estacionamento()
        {
            var task1 = Task.Run(async() => {
                this.token_ = await GetToken();
            });

            task1.Wait();

            GetUsuario();
            List <Recebimentos>             recebimentos             = new List <Recebimentos>();
            List <RecebimentosFiltrados>    recebimentosFiltrados    = new List <RecebimentosFiltrados>();
            List <UsuariosDoEstacionamento> usuariosDoEstacionamento = new List <UsuariosDoEstacionamento>();
            List <Solicitantes>             solicitacoes             = new List <Solicitantes>();
            List <Solicitantes>             solicitacoes2            = new List <Solicitantes>();
            List <Solicitantes>             solicitacoes3            = new List <Solicitantes>();

            //Recebimentos e Usuarios do Estacionamento
            Estacionamento estacionamento = new Estacionamento();
            var            task           = Task.Run(async() => {
                using (BaseController <Estacionamento> bUsuario = new BaseController <Estacionamento>())
                {
                    var valorRetorno = await bUsuario.GetObjectAsyncWithToken("Estacionamentos/EstacionamentoPorPessoa?IdPessoa=" + _usuario.IdPessoa, token_);
                    estacionamento   = valorRetorno.Data;
                }

                using (BaseController <List <Recebimentos> > bUsuario = new BaseController <List <Recebimentos> >())
                {
                    var valorRetorno = await bUsuario.GetObjectAsyncWithToken("Solicitacao/GetRecebimentos?idUsuario=" + _usuario.IdPessoa, token_);
                    recebimentos     = valorRetorno.Data;
                }

                using (BaseController <List <UsuariosDoEstacionamento> > bUsuario = new BaseController <List <UsuariosDoEstacionamento> >())
                {
                    var valorRetorno         = await bUsuario.GetObjectAsyncWithToken("Solicitacao/GetUsuariosDoEstacionamento?idUsuario=" + estacionamento.Id, token_);
                    usuariosDoEstacionamento = valorRetorno.Data;
                }

                using (BaseController <List <Solicitantes> > bUsuario = new BaseController <List <Solicitantes> >())
                {
                    var valorRetorno = await bUsuario.GetObjectAsyncWithToken("Solicitacao/GetSolicitacoesEmAberto?idUsuario=" + GetIdPessoa(), await GetToken());
                    solicitacoes     = valorRetorno.Data;
                }

                using (BaseController <List <Solicitantes> > bUsuario = new BaseController <List <Solicitantes> >())
                {
                    var valorRetorno = await bUsuario.GetObjectAsyncWithToken("Solicitacao/GetSolicitacoesParaFinalizar?idUsuario=" + GetIdPessoa(), await GetToken());
                    solicitacoes2    = valorRetorno.Data;
                }

                using (BaseController <List <Solicitantes> > bUsuario = new BaseController <List <Solicitantes> >())
                {
                    var valorRetorno = await bUsuario.GetObjectAsyncWithToken("Solicitacao/GetUsuariosAtivosSolicitacao?idUsuario=" + GetIdPessoa(), await GetToken());
                    solicitacoes3    = valorRetorno.Data;
                }
            });

            task.Wait();
            foreach (var item in recebimentos)
            {
                var it = item.MesAno.Split('-');
                RecebimentosFiltrados recebimentos1 = new RecebimentosFiltrados();
                recebimentos1.Mes    = int.Parse(it[0]);
                recebimentos1.Ano    = int.Parse(it[1]);
                recebimentos1.MesAno = recebimentos1.Mes + recebimentos1.Ano;
                recebimentos1.Valor  = item.Valor;
                recebimentosFiltrados.Add(recebimentos1);
            }
            if (solicitacoes3.Count == 1 && solicitacoes3.First().NomeCliente == null)
            {
                solicitacoes3 = new List <Solicitantes>();
            }
            ViewBag.UsuariosAtivos = solicitacoes3.Count;
            ViewBag.ValorHora      = estacionamento.ValorHora;
            ViewBag.Recebimentos   = recebimentosFiltrados?.OrderByDescending(x => x.MesAno).ToList() as List <RecebimentosFiltrados>;
            ViewBag.Usuarios       = usuariosDoEstacionamento?.OrderByDescending(x => x.PeriodoDe).ToList() as List <UsuariosDoEstacionamento>;
            ViewBag.InsereAlerta   = !estacionamento.TemEstacionamento;
            ViewBag.InsereAlerta2  = solicitacoes.Count > 0 && solicitacoes.First().NomeCliente != null ? true : false;
            ViewBag.InsereAlerta3  = solicitacoes2.Count > 0 && solicitacoes2.First().NomeCliente != null ? true : false;
            ViewBag.Nickname       = estacionamento.Proprietario.Nome;
            ViewBag.Cadastrar      = "Você precisa cadastrar um endereco para seu estacionamento. clique aqui.";
            ViewBag.Level          = 1;
            return(View());
        }
Esempio n. 60
0
 private List <string> Issue2545(List <string> arglist)
 {
     return(arglist?.OrderByDescending((string f) => f.Length).ThenBy((string f) => f.ToLower()).ToList());
 }