//Check the Sort Order to sort with corresponding column
 public void CheckSortOrder(string sortOrder, ref IEnumerable<Comment> comment)
 {
     switch (sortOrder)
     {
         case "Date_desc":
             comment = comment.OrderByDescending(u => u.PostedDate);
             break;
         case "PatientName":
             comment = comment.OrderBy(u => u.Patient.FullName);
             break;
         case "PatientName_desc":
             comment = comment.OrderByDescending(u => u.Patient.FullName);
             break;
         case "DoctorName":
             comment = comment.OrderBy(u => u.Doctor.FullName);
             break;
         case "DoctorName_desc":
             comment = comment.OrderByDescending(u => u.Doctor.FullName);
             break;
         case "Content":
             comment = comment.OrderBy(u => u.Content);
             break;
         case "Content_desc":
             comment = comment.OrderByDescending(u => u.Content);
             break;
         default:
             comment = comment.OrderBy(u => u.PostedDate);
             break;
     }
 }
 IEnumerable<Product> SortProducts(IEnumerable<Product> products, string sortOrder)
 {
     switch (sortOrder)
     {
         case NAME:
             products = products.OrderByDescending(s => s.name);
             break;
         case MANUNAME:
             products = products.OrderBy(s => s.Manufacturer);
             break;
         case MFGDISCOUNT:
             products = products.OrderByDescending(s => s.Manufacturer.mfgDiscount);
             break;
         case PRICE:
             products = products.OrderByDescending(s => s.price);
             break;
         case VENDOR:
             products = products.OrderByDescending(s => s.vendor);
             break;
         default:
             products = products.OrderByDescending(s => s.productID);
             break;
     }
     return products;
 }
        public async Task<IEnumerable<ParkingLot>> CreateList(IEnumerable<ParkingLot> items)
        {
            var mainVm = ServiceLocator.Current.GetInstance<MainViewModel>();
            var filter = mainVm.ParkingLotFilterMode;
            var orderAsc = mainVm.ParkingLotFilterAscending;
            var alphabeticalSortingFunc = new Func<ParkingLot, string>(x => x.Name);
            switch (filter)
            {
                case ParkingLotFilterMode.Alphabetically:
                    return orderAsc ? items.OrderBy(alphabeticalSortingFunc) : items.OrderByDescending(alphabeticalSortingFunc);
                case ParkingLotFilterMode.Availability:
                    var availabilitySortingFunc = new Func<ParkingLot, double>(x =>
                    {
                        if (x.TotalLots == 0)
                        {
                            return 2; //they're always last of the list
                        }
                        return 1 - ((double) x.FreeLots / (double)x.TotalLots); //something between 0 and 1
                    });
                    return orderAsc ? items.OrderBy(availabilitySortingFunc).ThenBy(alphabeticalSortingFunc) : items.OrderByDescending(availabilitySortingFunc).ThenBy(alphabeticalSortingFunc);
                case ParkingLotFilterMode.Distance:
                    var userPos = await ServiceLocator.Current.GetInstance<GeolocationService>().GetUserLocation();
                    if (userPos == null)
                    {
                        mainVm.ParkingLotFilterMode = ParkingLotFilterMode.Alphabetically;
                        return await CreateList(items);
                    }

                    var distanceSortingFunc = new Func<ParkingLot, double>(x => x?.Coordinates?.Point == null ? double.MaxValue : userPos.Coordinate.Point.GetDistanceTo(x.Coordinates.Point));
                    return orderAsc ? items.OrderBy(distanceSortingFunc).ThenBy(alphabeticalSortingFunc) : items.OrderByDescending(distanceSortingFunc).ThenBy(alphabeticalSortingFunc);
                default:
                    return orderAsc ? items.OrderBy(alphabeticalSortingFunc) : items.OrderByDescending(alphabeticalSortingFunc);
            }
        }
        private IEnumerable <IPublishedContent>?SortByDefaultPropertyValue(IEnumerable <IPublishedContent>?contents, SortExpression sortExpression)
        {
            switch (sortExpression.Property?.Alias)
            {
            case "id":
                return(sortExpression.Direction == "ascending"
                        ? contents?.OrderBy(x => x.Id)
                        : contents?.OrderByDescending(x => x.Id));

            case "createDate":
                return(sortExpression.Direction == "ascending"
                        ? contents?.OrderBy(x => x.CreateDate)
                        : contents?.OrderByDescending(x => x.CreateDate));

            case "publishDate":
                return(sortExpression.Direction == "ascending"
                        ? contents?.OrderBy(x => x.UpdateDate)
                        : contents?.OrderByDescending(x => x.UpdateDate));

            case "name":
                return(sortExpression.Direction == "ascending"
                        ? contents?.OrderBy(x => x.Name)
                        : contents?.OrderByDescending(x => x.Name));

            default:
                return(sortExpression.Direction == "ascending"
                        ? contents?.OrderBy(x => x.Name)
                        : contents?.OrderByDescending(x => x.Name));
            }
        }
Esempio n. 5
0
		private IEnumerable<IGrouping<string, RepositoryDetailedModel>> CreateGroupedItems(IEnumerable<RepositoryDetailedModel> model)
        {
            var order = Repositories.Filter.OrderBy;

            if (order == RepositoriesFilterModel.Order.LastUpdated)
            {
                var a = model.OrderByDescending(x => x.UtcLastUpdated).GroupBy(x => FilterGroup.IntegerCeilings.First(r => r > x.UtcLastUpdated.TotalDaysAgo()));
                a = Repositories.Filter.Ascending ? a.OrderBy(x => x.Key) : a.OrderByDescending(x => x.Key);
                return FilterGroup.CreateNumberedGroup(a, "Days Ago", "Updated");
            }
            if (order == RepositoriesFilterModel.Order.CreatedOn)
            {
                var a = model.OrderByDescending(x => x.UtcCreatedOn).GroupBy(x => FilterGroup.IntegerCeilings.First(r => r > x.UtcCreatedOn.TotalDaysAgo()));
                a = Repositories.Filter.Ascending ? a.OrderBy(x => x.Key) : a.OrderByDescending(x => x.Key);
                return FilterGroup.CreateNumberedGroup(a, "Days Ago", "Created");
            }
            if (order == RepositoriesFilterModel.Order.Owner)
            {
                var a = model.OrderBy(x => x.Name).GroupBy(x => x.Owner);
                a = Repositories.Filter.Ascending ? a.OrderBy(x => x.Key) : a.OrderByDescending(x => x.Key);
                return a.ToList();
            }

            return null;
        }
        public IPagedList<Facility> getList(string sortOrder, string currentFilter, int? page, IEnumerable<Facility> data)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.Name = String.IsNullOrEmpty(sortOrder) ? "Name_desc" : "";
            ViewBag.IsFree = sortOrder == "IsFree" ? "IsFree_desc" : "IsFree";
            ViewBag.Enabled = sortOrder == "Enabled" ? "Enabled_desc" : "Enabled";
            ViewBag.SO_RateTypeId = sortOrder == "RateTypeId" ? "RateTypeId_desc" : "RateTypeId";
            ViewBag.Rate = sortOrder == "Rate" ? "Rate_desc" : "Rate";
            ViewBag.IsGST = sortOrder == "IsGST" ? "IsGST_desc" : "IsGST";
            switch (sortOrder)
            {
                case "Name_desc":
                    data = data.OrderByDescending(s => s.Name );
                    break;
                case "IsFree":
                    data = data.OrderBy(s => s.IsFree);
                    break;
                case "IsFree_desc":
                    data = data.OrderByDescending(s => s.IsFree);
                    break;
                case "Enabled":
                    data = data.OrderBy(s => s.Enabled);
                    break;
                case "Enabled_desc":
                    data = data.OrderByDescending(s => s.Enabled);
                    break;
                case "RateTypeId":
                    data = data.OrderBy(s => s.RateTypeId);
                    break;
                case "RateTypeId_desc":
                    data = data.OrderByDescending(s => s.RateTypeId);
                    break;
                case "Rate":
                    data = data.OrderBy(s => s.Rate);
                    break;
                case "Rate_desc":
                    data = data.OrderByDescending(s => s.Rate);
                    break;
                case "IsGST":
                    data = data.OrderBy(s => s.IsGST);
                    break;
                case "IsGST_desc":
                    data = data.OrderByDescending(s => s.IsGST);
                    break;
                case "":
                default:
                    data = data.OrderBy(s => s.Name);
                    break;
            }

            int pageSize = Configurations.PageSize(); 
            int pageNumber = (page ?? 1);
            return data.ToPagedList(pageNumber, pageSize);
        }
        public _ContentFeedViewModel(IEnumerable<Content> content, Guid? authorId, string groupUrl, int contentPerPage = 5)
        {
            AuthorId = authorId;
            GroupUrl = groupUrl;

            if (authorId.HasValue)
                content = content.OrderByDescending(x => x.IsUserAttached(authorId.Value));
            if (!string.IsNullOrEmpty(groupUrl))
                content = content.OrderByDescending(x => x.IsGroupAttached(groupUrl));

            FeedContent = new PaginationList<_ContentFeed_ContentViewModel, Content>(content, contentPerPage, x => new _ContentFeed_ContentViewModel(x));
        }
Esempio n. 8
0
        private int WriteWith(IEnumerable<TfsChangesetInfo> tfsParents, string refToWrite, Func<TfsChangesetInfo, string, int> write)
        {
            switch (tfsParents.Count())
            {
                case 1:
                    var changeset = tfsParents.First();
                    return write(changeset, refToWrite);
                case 0:
                    _stdout.WriteLine("No TFS parents found!");
                    return GitTfsExitCodes.InvalidArguments;
                default:
                    if (tfsParents.Select(x => x.Remote.IsSubtree ? x.Remote.OwningRemoteId : x.Remote.Id).Distinct().Count() == 1)
                    {
                        //this occurs when we have merged in a subtree, at the subtree merge commit there will be a tfsParent for the
                        //subtree owner in addition to the one for the subtree itself.  In this case, we will use the subtree owner, since
                        //we are in the main history line and not a subtree line.
                        var lastChangeSet = tfsParents.OrderByDescending(x => x.ChangesetId).First();
                        if (lastChangeSet.Remote.IsSubtree)
                            lastChangeSet.Remote = _globals.Repository.ReadTfsRemote(lastChangeSet.Remote.OwningRemoteId);
                        _stdout.WriteLine(string.Format("Basing from parent '{0}:{1}', use -i to override", lastChangeSet.Remote.Id, lastChangeSet.ChangesetId));
                        return write(lastChangeSet, refToWrite);
                    }

                    _stdout.WriteLine("More than one parent found! Use -i to choose the correct parent from: ");
                    foreach (var parent in tfsParents)
                    {
                        _stdout.WriteLine("  " + parent.Remote.Id);
                    }
                    return GitTfsExitCodes.InvalidArguments;
            }
        }
Esempio n. 9
0
        public void CacheRssResults(IIndexer indexer, IEnumerable<ReleaseInfo> releases)
        {
            lock (cache)
            {
                var trackerCache = cache.Where(c => c.TrackerId == indexer.ID).FirstOrDefault();
                if (trackerCache == null)
                {
                    trackerCache = new TrackerCache();
                    trackerCache.TrackerId = indexer.ID;
                    trackerCache.TrackerName = indexer.DisplayName;
                    cache.Add(trackerCache);
                }

                foreach(var release in releases.OrderByDescending(i=>i.PublishDate))
                {
                    var existingItem = trackerCache.Results.Where(i => i.Result.Guid == release.Guid).FirstOrDefault();
                    if (existingItem == null)
                    {
                        existingItem = new CachedResult();
                        existingItem.Created = DateTime.Now;
                        trackerCache.Results.Add(existingItem);
                    }

                    existingItem.Result = release;
                }

                // Prune cache
                foreach(var tracker in cache)
                {
                    tracker.Results = tracker.Results.OrderByDescending(i => i.Created).Take(MAX_RESULTS_PER_TRACKER).ToList();
                }
            }
        }
Esempio n. 10
0
 public IEnumerable<MapObject> Order(ViewportBase viewport, IEnumerable<MapObject> mapObjects)
 {
     var vp3 = viewport as Viewport3D;
     if (vp3 == null) return mapObjects;
     var cam = vp3.Camera.Location.ToCoordinate();
     return mapObjects.OrderByDescending(x => (x.BoundingBox.Center - cam).LengthSquared());
 }
Esempio n. 11
0
        public void Publish(IEnumerable<RouteDescriptor> routes)
        {
            var routesArray = routes.OrderByDescending(r => r.Priority).ToArray();

            // this is not called often, but is intended to surface problems before
            // the actual collection is modified
            var preloading = new RouteCollection();
            foreach (var route in routesArray)
                preloading.Add(route.Name, route.Route);

            using (_routeCollection.GetWriteLock()) {
                // existing routes are removed while the collection is briefly inaccessable
                var cropArray = _routeCollection
                    .OfType<ShellRoute>()
                    .Where(sr => sr.ShellSettingsName == _shellSettings.Name)
                    .ToArray();

                foreach(var crop in cropArray) {
                    _routeCollection.Remove(crop);
                }

                // new routes are added
                foreach (var routeDescriptor in routesArray) {
                    //_routeCollection.Add(route.Name, _shellRouteFactory(_shellSettings.Name, route.Route));
                    _routeCollection.Add(routeDescriptor.Name, _shellRouteFactory(routeDescriptor.Route));
                }
            }
        }
Esempio n. 12
0
            public PipeList(PipeManager pipeManager, IEnumerable<IPipe> pipes)
            {
                _pipeManager = pipeManager;
                _pipes = pipes.OrderByDescending(x => x.Priority).ToList();

                ReloadEnabledPipes();
            }
Esempio n. 13
0
        private IEnumerable <Cell> GetAffectedThreatsCells(IEnumerable <IThreatEventMitigation> mitigations)
        {
            IEnumerable <Cell> result = null;

            var list = mitigations?
                       .OrderByDescending(x => x.Strength, new StrengthComparer())
                       .ThenBy(x => x.ThreatEvent.Parent.Name)
                       .ThenBy(x => x.ThreatEvent.Name).ToArray();

            if (list?.Any() ?? false)
            {
                var cells = new List <Cell>();

                foreach (var item in list)
                {
                    cells.Add(new Cell($"{item.ThreatEvent.Parent.Name}",
                                       $"[{item.Model.GetIdentityTypeInitial(item.ThreatEvent.Parent)}] ", null, new [] { item.ThreatEvent.ParentId }));
                    cells.Add(new Cell(item.ThreatEvent.Name, null, null,
                                       new [] { item.ThreatEvent.Id, item.ThreatEvent.ThreatTypeId }));
                    cells.Add(new Cell(item.Strength.Name ?? DefaultStrength.Average.GetEnumLabel()));
                    cells.Add(new Cell(item.Status.GetEnumLabel()));
                }

                result = cells;
            }

            return(result);
        }
Esempio n. 14
0
        IPackageInfo PackageInfo(IEnumerable<IPackageInfo> packageInfos)
        {
            if (Version != null)
                return packageInfos.OrderByDescending(x => x.Version).FirstOrDefault(x => x.Version.Major.Equals(Version.Major) && x.Version.Major.Equals(Version.Major));

            return packageInfos.Last();
        }
Esempio n. 15
0
        public static CUFsListViewModel BuildPage(int pagenr, int itemsnr, String order,
            IEnumerable<CufRepoModel> repository, String title, String method, Boolean hasVersion)
        {
            int amountPages = ((repository.Count() + itemsnr - 1) / itemsnr);
            CUFsListModel clm = new CUFsListModel(title);

            repository = (order == "Asc") ? repository.OrderBy(cuf => cuf.Name) : repository.OrderByDescending(cuf => cuf.Name);

            foreach (var cuf in repository.Skip(pagenr * itemsnr).Take(itemsnr))
            {
                if (hasVersion)
                    clm.AddURIParams(cuf.Name + " [ V: " + cuf.Version + " ]", method, cuf.Acr, cuf.Version); //proposal-version
                else
                    clm.AddURIParams(cuf.Name, method, cuf.Acr);

            }

            CUFsListViewModel clvm = new CUFsListViewModel();
            clvm.CUFList = clm.GetCUFsListModel();
            clvm.PageNumber = pagenr;
            clvm.ItemsNumber = itemsnr;
            clvm.Order = order;
            clvm.AmountPage = amountPages;
            clvm.LastPage = false;
            clvm.ItemsPerPage = itemsPerPage;
            clvm.OrderPage = orderOptions;

            clvm.Method = hasVersion ? "PageVersion" : "Page";

            if (clvm.CUFList.Count() < itemsnr ||
                repository.Skip((pagenr + 1) * itemsnr).Take(itemsnr).Count() == 0)
                clvm.LastPage = true;

            return clvm;
        }
 public Wechselgeld BerechneWechselgeld(IEnumerable<Münze> verfügbareMünzen, Cents betrag)
 {
     var münzen = verfügbareMünzen.OrderByDescending(i => i).ToArray();
     var lösung = LöseRekursiv(münzen, 0, betrag);
     if (lösung == null) throw new Exception("keine Lösung gefunden");
     return lösung.Item2;
 }
 private static IEnumerable<string> NewMethod(IEnumerable<Product> allProducts)
 {
     return allProducts
                     .OrderByDescending(p => p.Price)
                     .Take(5)
                     .Select(p => p.Nome);
 }
Esempio n. 18
0
        private IEnumerable<DataGridViewRow> _SortRowsByColumn(IEnumerable<DataGridViewRow> rows)
        {
            var get_row_mod_name = new Func<DataGridViewRow, string>(row => ((GUIMod) row.Tag).Name);
            Func<DataGridViewRow, string> sort_fn;

            // XXX: There should be a better way to identify checkbox columns than hardcoding their indices here
            if (this.m_Configuration.SortByColumnIndex < 2)
            {
                sort_fn = new Func<DataGridViewRow, string>(row =>
                {
                    var cell = row.Cells[this.m_Configuration.SortByColumnIndex];
                    if (cell.ValueType == typeof (bool))
                    {
                        return (bool) cell.Value ? "a" : "b";
                    }
                    // It's a "-" cell so let it be ordered last
                    return "c";
                });
            }
            else
            {
                sort_fn =
                    new Func<DataGridViewRow, string>(
                        row => row.Cells[this.m_Configuration.SortByColumnIndex].Value.ToString());
            }
            // Update the column sort glyph
            this.ModList.Columns[this.m_Configuration.SortByColumnIndex].HeaderCell.SortGlyphDirection =
                this.m_Configuration.SortDescending ? SortOrder.Descending : SortOrder.Ascending;
            // The columns will be sorted by mod name in addition to whatever the current sorting column is
            if (this.m_Configuration.SortDescending)
            {
                return rows.OrderByDescending(sort_fn).ThenBy(get_row_mod_name);
            }
            return rows.OrderBy(sort_fn).ThenBy(get_row_mod_name);
        }
        public TransitionPredictions(IEnumerable<TransitionEmissions> transitionEmissions)
        {
            if (transitionEmissions == null)
            {
                return;
            }

            this.TransitionEmissions = transitionEmissions.OrderByDescending(emissions => emissions.Probability);

            if (!this.TransitionEmissions.Any())
            {
                return;
            }

            var expectedAmounts = new List<double>();
            var standardDeviations = new List<double>();

            var runningProbability = (double)0;
            var i = 0;
            while (runningProbability < 0.5)
            {
                var transitionEmission = this.TransitionEmissions.ElementAt(i);
                expectedAmounts.Add(transitionEmission.ExpectedValue);
                standardDeviations.Add(transitionEmission.StandardDeviation);
                runningProbability += transitionEmission.Probability;
                i++;
            }

            this.MinimumSuggestedAmount = expectedAmounts.Average() + standardDeviations.Average();
        }
Esempio n. 20
0
 public override IEnumerable<IUnit> PickNextTargets(IEnumerable<IUnit> candidateTargets)
 {
     return candidateTargets
         .OrderByDescending(target => target.HealthPoints)
         .ThenBy(target => target.Name)
         .Take(3);
 }
 public override IEnumerable<IUnit> PickNextTargets(IEnumerable<IUnit> candidateTargets)
 {
     ////-picks 3 targets with most health points.
     //// If there are several targets with equal health points, picks those with alphabetically first name.
     this.ValidateTargets(candidateTargets);
     return candidateTargets.OrderByDescending(t => t.HealthPoints).ThenBy(t => t.Name).Take(3).ToList();
 }
Esempio n. 22
0
        internal static object GetJsonForAoutPayment(IEnumerable<Payment> payment, int page)
        {
            if (payment == null)
            {
                return string.Empty;
            }

            var result = new
            {
                total = payment.Count(),
                page,
                records = payment.Count(),
                rows = payment.OrderByDescending(c => c.PaymentDate).Select(x => new
                {
                    id = x.Id,
                    cell = new[]
                    {
                        x.PaymentDate.ToString("dd.MM.yyyy"),
                        x.FromAccount.CardNumber.ToString(),
                        x.ToAccount.Description,
                        x.TotalAmount.ToString(),
                        x.Currency.Abbreveature
                    }
                })
            };

            return result;
        }
Esempio n. 23
0
 public DynamicContainer(IEnumerable<IDummyFactory> dummyFactories, IEnumerable<IFakeConfigurator> fakeConfigurators)
 {
     this.allDummyFactories = dummyFactories.OrderByDescending(factory => factory.Priority).ToArray();
     this.allFakeConfigurators = fakeConfigurators.OrderByDescending(factory => factory.Priority).ToArray();
     this.cachedDummyFactories = new ConcurrentDictionary<Type, IDummyFactory>();
     this.cachedFakeConfigurators = new ConcurrentDictionary<Type, IFakeConfigurator>();
 }
Esempio n. 24
0
        public async Task GenerateContentAsync(HttpContext context, IEnumerable <IFileInfo> contents)
        {
            context.Response.ContentType = "text/html;charset=utf-8";
            await context.Response.WriteAsync("<html><head><title>Index</title>");

            await context.Response.WriteAsync("<style> div.ff {  width: 600px;  } div { height: 30px; display:flex; align-items: center; } div.aa { flex:5; } div.bb { flex:2.5; } div.cc { flex:2.5; }</style>");

            await context.Response.WriteAsync("<body><div class='ff'>");

            await context.Response.WriteAsync($"<div class='aa'>文件名</div>");

            await context.Response.WriteAsync($"<div class='bb'>文件大小</div>");

            await context.Response.WriteAsync($"<div class='cc'>时间</div>");

            await context.Response.WriteAsync($"</div>");

            IOHelper ge  = new IOHelper();
            var      con = contents?.OrderByDescending(x => x.LastModified).ToList() ?? new List <IFileInfo>();

            foreach (var file in con)
            {
                string href = $"{context.Request.Path.Value.TrimEnd('/')}/{file.Name}";
                await context.Response.WriteAsync($"<div class='ff'>");

                await context.Response.WriteAsync($"<div class='aa'><a href='{href}'>{file.Name}</a></div>");

                await context.Response.WriteAsync($"<div class='bb'>{ge.CountSize(file.Length)}</div>");

                await context.Response.WriteAsync($"<div class='cc'>{file.LastModified.LocalDateTime}</div>");

                await context.Response.WriteAsync($"</div>");
            }
            await context.Response.WriteAsync("</body></html>");
        }
Esempio n. 25
0
        /// <summary>
        ///     Fill menu items on grill.
        /// </summary>
        /// <param name="menuItems">All items to prepare.</param>
        /// <returns>Added on grill items.</returns>
        public IEnumerable<GrillMenuItem> FillGrillItems(IEnumerable<GrillMenuItem> menuItems)
        {
            _menuItemsOnGrill = new List<GrillMenuItem>();
            foreach (var grillMenuItem in menuItems.OrderByDescending(i => i.Square).ToList())
            {
                if (AddMenuItemIfCan(grillMenuItem))
                {
                    // todo: replace console output into Grill project.
                    Console.WriteLine("Added {0}", grillMenuItem);
                    Console.WriteLine(@"/------------------------------\");
                    for (var i = 0; i < Heigth; i++)
                    {
                        Console.Write("|");
                        for (var j = 0; j < Width; j++)
                        {
                            Console.Write(IsBusyPoint(j, i) ? "x" : ".");
                        }

                        Console.Write("|\n");
                    }

                    Console.WriteLine(@"\------------------------------/");
                    Console.ReadKey();
                    Console.Clear();
                }

            }

            return _menuItemsOnGrill;
        }
Esempio n. 26
0
        public PostViewModel(int totalPosts, 
            int totalComments, 
            IEnumerable<Post> featured,
            IEnumerable<Post> subsonic,
            IEnumerable<Post> opinion,
            IEnumerable<Comment> comments)
        {
            TotalPosts = totalPosts;
            TotalComments = totalComments;

            if (featured != null)
                FeaturePosts = featured.OrderByDescending(x => x.PublishedAt).Take(2).ToList();
            else
                FeaturePosts = new List<Post>();

            if (subsonic != null)
                SubSonicPosts = subsonic.OrderByDescending(x => x.PublishedAt).Take(5).ToList();
            else
                SubSonicPosts = new List<Post>();

            if (opinion != null)
                OpinionPosts = opinion.OrderByDescending(x => x.PublishedAt).Take(5).ToList();
            else
                OpinionPosts = new List<Post>();

            if (comments != null)
                RecentComments = comments.OrderByDescending(x => x.CreatedAt).Take(5).ToList();
            else
                RecentComments = new List<Comment>();
        }
        /// <summary>
        /// Constructor
        /// </summary>
        public AvailableNetworkGroupPack(
            InterfaceInfo interfaceInfo,
            NetworkIdentifier ssid,
            BssType bssType,
            int signalQuality,
            bool isSecurityEnabled,
            string profileName,
            AuthenticationAlgorithm authenticationAlgorithm,
            CipherAlgorithm cipherAlgorithm,
            IEnumerable <BssNetworkPack> bssNetworks) : base(
                interfaceInfo: interfaceInfo,
                ssid: ssid,
                bssType: bssType,
                signalQuality: signalQuality,
                isSecurityEnabled: isSecurityEnabled,
                profileName: profileName,
                authenticationAlgorithm: authenticationAlgorithm,
                cipherAlgorithm: cipherAlgorithm)
        {
            this.BssNetworks = Array.AsReadOnly(bssNetworks?.OrderByDescending(x => x.LinkQuality).ToArray() ?? new BssNetworkPack[0]);
            if (!this.BssNetworks.Any())
            {
                return;
            }

            var highestLinkQualityNetwork = this.BssNetworks.First();

            LinkQuality = highestLinkQualityNetwork.LinkQuality;
            Frequency   = highestLinkQualityNetwork.Frequency;
            Band        = highestLinkQualityNetwork.Band;
            Channel     = highestLinkQualityNetwork.Channel;
        }
Esempio n. 28
0
        public void Publish(IEnumerable<RouteDescriptor> routes, RequestDelegate pipeline)
        {
            var orderedRoutes = routes
                .OrderByDescending(r => r.Priority)
                .ToList();

            string routePrefix = "";
            if (!String.IsNullOrWhiteSpace(_shellSettings.RequestUrlPrefix))
            {
                routePrefix = _shellSettings.RequestUrlPrefix + "/";
            }

            orderedRoutes.Insert(0, new RouteDescriptor
            {
                Route = new Route("Default", "{area}/{controller}/{action}/{id?}")
            });


            var inlineConstraint = _routeBuilder.ServiceProvider.GetService<IInlineConstraintResolver>();

            foreach (var route in orderedRoutes)
            {
                IRouter router = new TemplateRoute(
                    _routeBuilder.DefaultHandler,
                    route.Route.RouteName,
                    routePrefix + route.Route.RouteTemplate,
                    route.Route.Defaults,
                    route.Route.Constraints,
                    route.Route.DataTokens,
                    inlineConstraint);

                _routeBuilder.Routes.Add(new TenantRoute(_shellSettings, router, pipeline));
            }
        }
 public Wechselgeld BerechneWechselgeld(IEnumerable<Münze> verfügbareMünzen, Cents betrag)
 {
     var münzen = verfügbareMünzen.OrderByDescending(i => i);
     var initial = Tuple.Create((Wechselgeld) new AnzahlMünzePaar[] {}, betrag);
     var gewählteMünzen = münzen.Aggregate(initial, AusgabeUndRestbetragFürMünze);
     return gewählteMünzen.Item1;
 }
        public IEnumerable<IPackage> GetUpdates(IEnumerable<IPackage> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<System.Runtime.Versioning.FrameworkName> targetFrameworks, IEnumerable<IVersionSpec> versionConstraints)
        {
            // only keep the latest version of each package Id to mimic the behavior of nuget.org GetUpdates() service method
            packages = packages.OrderByDescending(p => p.Version).Distinct(PackageEqualityComparer.Id);

            return this.GetUpdatesCore(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints);
        }
Esempio n. 31
0
 private static List<NewsItem> SortNews(IEnumerable<NewsItem> items)
 {
     //Order by NewsByYear node, then by publish or create date
     return items.OrderByDescending(i => i.Parent<NewsByYear>().Name)
             .ThenByDescending(i => i.PublishDate != default(DateTime) ? i.PublishDate : i.CreateDate)
             .ToList();
 }
Esempio n. 32
0
        private static void DownloadVideo(IEnumerable<VideoInfo> videoInfos)
        {
            /*
             * Select the first .mp4 video with 360p resolution
             */
            VideoInfo video = videoInfos
                .OrderByDescending(v => v.Resolution).First(info => info.VideoType == VideoType.Mp4);

            /*
             * If the video has a decrypted signature, decipher it
             */
            if(video.RequiresDecryption) {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the video downloader.
             * The first argument is the video to download.
             * The second argument is the path to save the video file.
             */
            var videoDownloader = new VideoDownloader(video,
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                RemoveIllegalPathCharacters(video.Title) + video.VideoExtension));

            // Register the ProgressChanged event and print the current progress
            videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

            /*
             * Execute the video downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            videoDownloader.Execute();
        }
 public MicroDataProcessor(IEnumerable<MicroDataEntry> microDataEntries)
 {
     if (microDataEntries != null)
     {
         _microDataEntries = microDataEntries.OrderByDescending(o => o.ContentType.GetValueOrDefault(Guid.Empty));
     }
 }
Esempio n. 34
0
        public void OutputRunStats(TimeSpan totalRuntime, IEnumerable<RunStats> runners, List<string> skippedTests)
        {
            var sb = new StringBuilder();

            sb.AppendLine(_ganttChartBuilder.GenerateGanttChart(runners));

            sb.AppendLine("<pre>");
            sb.AppendLine("Total Runtime: " + totalRuntime.ToString());
            foreach (var r in runners.OrderByDescending(t => t.RunTime))
            {
                AppendTestFinishedLine(sb, r);
            }

            if (skippedTests.Count > 0)
            {
                sb.AppendLine();
                sb.AppendLine("Did not run:");
                foreach (var r in skippedTests)
                {
                    sb.AppendFormat("'{0}'", r);
                    sb.AppendLine();
                }
            }
            sb.AppendLine("</pre>");

            File.WriteAllText(_settings.ResultsStatsFilepath, sb.ToString());
        }
Esempio n. 35
0
 public static IOrderedEnumerable <T> OrderBy <T, TKey>(
     IEnumerable <T> enumerable,
     Func <T, TKey> keySelector,
     bool ascending
     )
 {
     return(ascending ? enumerable?.OrderBy(keySelector) : enumerable?.OrderByDescending(keySelector));
 }
        public bool ConditionMet(DateTime learnStartDate, IEnumerable <IFcsContractAllocation> contractAllocations)
        {
            var latestStopNewStartsFromDate = contractAllocations?
                                              .OrderByDescending(ca => ca.StartDate)
                                              .FirstOrDefault()
                                              ?.StopNewStartsFromDate;

            return(latestStopNewStartsFromDate != null && learnStartDate >= latestStopNewStartsFromDate);
        }
 /// <summary>
 ///     Orders the enemy minions.
 /// </summary>
 /// <param name="minions">
 ///     The minions.
 /// </param>
 /// <returns>
 ///     The <see cref="List{T}" /> of <see cref="AIMinionClient" />.
 /// </returns>
 private static List <AIMinionClient> OrderEnemyMinions(IEnumerable <AIMinionClient> 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. 38
0
 private static IEnumerable <VersionInfo> ToVersionInfo(IEnumerable <IPackageSearchMetadata> packages)
 {
     return(packages?
            .OrderByDescending(m => m.Identity.Version, VersionComparer.VersionRelease)
            .Select(m => new VersionInfo(m.Identity.Version, m.DownloadCount)
     {
         PackageSearchMetadata = m
     }));
 }
Esempio n. 39
0
        public static PaymentReceiptTemplateBO Map(IEnumerable <MemberSubscribedPlan> memberSubscribedPlans, Member member,
                                                   IEnumerable <MemberPaymentDetail> memberPaymentDetails, string html)
        {
            var memberAddress = member.MemberAddress?.FirstOrDefault(a => a.AddressTypeId == (int)AddressType.Primary);

            var paymentReiptTemplateBO = new PaymentReceiptTemplateBO()
            {
                ExternalId        = member.ExternalId,
                FullName          = $"{member.MemberDetail.FirstName} {member.MemberDetail.LastName}",
                Address           = $"{memberAddress?.AddressLine1} {memberAddress?.AddressLine2}",
                City              = memberAddress?.City,
                State             = memberAddress?.StateCode,
                Zip               = memberAddress?.ZipCode,
                Phone             = GetFormattedPhoneNumber(member.MemberDetail.PhoneNumber),
                Email             = member.MemberDetail.EmailId,
                Type              = MemberConstants.Type,
                PaymentNumber     = memberPaymentDetails?.OrderByDescending(a => a.PaidDate).FirstOrDefault().PaymentNumber?.ToString(),
                PaidDateTitle     = memberPaymentDetails?.OrderByDescending(a => a.PaidDate).FirstOrDefault()?.PaidDate?.ToString("MMMM dd,yyyy"),
                PaidDate          = string.Format("{0} at {1}", memberPaymentDetails?.OrderByDescending(a => a.PaidDate).FirstOrDefault()?.PaidDate?.ToString("MM/dd/yyyy"), memberPaymentDetails?.OrderByDescending(a => a.PaidDate).FirstOrDefault()?.PaidDate?.ToString("t")),
                PayDate           = $"{memberPaymentDetails?.OrderByDescending(a => a.PaidDate).FirstOrDefault()?.PaidDate?.ToString("MMMM dd,yyyy")} at {memberPaymentDetails?.OrderByDescending(a => a.PaidDate).FirstOrDefault()?.PaidDate?.ToString("t")}",
                Status            = memberPaymentDetails?.OrderByDescending(a => a.PaidDate).FirstOrDefault()?.Status,
                TransactionStatus = memberPaymentDetails?.OrderByDescending(a => a.PaidDate).FirstOrDefault()?.Status,
                OrderId           = memberPaymentDetails?.OrderByDescending(a => a.PaidDate).FirstOrDefault()?.InvoiceId,
                TransactionId     = memberPaymentDetails?.OrderByDescending(a => a.TransactionId).FirstOrDefault()?.TransactionId,
                CardNumber        = member.MemberSubscription.FirstOrDefault().CardOrAccountNumber,
                Html              = html
            };

            var method = memberPaymentDetails?.OrderByDescending(a => a.PaidDate).FirstOrDefault()?.Method;

            paymentReiptTemplateBO.CardType = method == "ACH" ? "ACH" :
                                              Enum.GetName(typeof(CCType), member.MemberSubscription.FirstOrDefault().CardType.GetValueOrDefault());
            var builder = new StringBuilder();

            foreach (var subscribedPlan in memberSubscribedPlans)
            {
                builder.Append($"<tr><td style=\"padding: 3px;vertical-align: top;\">{subscribedPlan.Plan.Product.Name}<br> {Enum.GetName(typeof(FamilyIndicator), subscribedPlan.FamilyIndicator)} - ID: {subscribedPlan.Plan.Product.ProductCode} - Payment: {paymentReiptTemplateBO.PaymentNumber} <br> </td></tr>");
            }
            paymentReiptTemplateBO.Products = builder.ToString();
            decimal amountTotal = 0;

            foreach (var mpd in memberPaymentDetails)
            {
                amountTotal += mpd.PaidAmount.GetValueOrDefault();
            }
            paymentReiptTemplateBO.TotalAmount = amountTotal.ToString("C");
            return(paymentReiptTemplateBO);
        }
Esempio n. 40
0
        // GET: api/EventsOfMatches?MatchId=5
        public IEnumerable <EventsOfMatches> GetEventsOfMatchesByMatchId(int MatchId)
        {
            IEnumerable <EventsOfMatches> eventsList = _dystirDBContext.EventsOfMatches.Where(x => x.MatchId == MatchId);
            var sortedEventList = eventsList?
                                  .OrderByDescending(x => x.EventPeriodId ?? 0)
                                  .ThenByDescending(x => x.EventTotalTime)
                                  .ThenByDescending(x => x.EventMinute)
                                  .ThenByDescending(x => x.EventOfMatchId);

            return(sortedEventList ?? Enumerable.Empty <EventsOfMatches>());
        }
Esempio n. 41
0
        public OrderBook(string source, AssetPair assetPair, IEnumerable <LimitOrder> bids, IEnumerable <LimitOrder> asks, DateTime timestamp)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(source));
            Debug.Assert(assetPair != null);

            Source    = source;
            AssetPair = assetPair;
            Bids      = bids?.OrderByDescending(x => x.Price).ToList();
            Asks      = asks?.OrderBy(x => x.Price).ToList();
            Timestamp = timestamp;
        }
        private async Task <DeploymentServiceListModel> GetListAsync()
        {
            IEnumerable <DeploymentServiceModel> deployments = null;
            var response = await this.client.GetAllAsync(DeploymentsCollection);

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

            return(new DeploymentServiceListModel(deployments?.OrderByDescending(x => x.CreatedDateTimeUtc).ToList()));
        }
        public async Task <ActionResult> UserRepos(string reposUrl)
        {
            if (string.IsNullOrEmpty(reposUrl))
            {
                throw new ArgumentNullException(nameof(reposUrl));
            }

            IEnumerable <GitHubUserRepository> userRepos = await _gitHubService.GetUserRepos(reposUrl);

            var model = new GitHubUserReposModel
            {
                Repositories = userRepos?.OrderByDescending(x => x.StargazersCount).Take(5)
                               .OrderByDescending(x => x.Updated) // If all repos have stargazer counts the same, order by updated date
                               .OrderByDescending(x => x.StargazersCount).ToList() ?? new List <GitHubUserRepository>()
            };

            return(PartialView("_UserRepositories", model));
        }
Esempio n. 44
0
        private VideoInfo GetVideoInfo(LinkInfo linkInfo, out string videoName, out string videoFilePath)
        {
            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(linkInfo.URL, false);

            // Select the first video by type with highest AudioBitrate
            VideoInfo videoInfo = videoInfos
                                  ?.OrderByDescending(info => info.AudioBitrate)
                                  ?.First();

            //wrap whole thing in null object check
            if (videoInfo != null)
            {
                // This is must, cause we decrypting only this video
                if (videoInfo.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(videoInfo);
                }
            }

            //string fileBaseName = linkInfo.FileName == null ? videoInfo.Title.ToSafeFileName() : linkInfo.FileName.ToSafeFileName();
            string fileBaseName = string.Empty;

            //null check the info again
            if (videoInfo != null)
            {
                fileBaseName = linkInfo.FileName == null?videoInfo.Title.ToSafeFileName() : linkInfo.FileName.ToSafeFileName();
            }

            videoName = fileBaseName;

            //videoFilePath = Path.Combine(ExportVideoDirPath, fileBaseName + videoInfo.VideoExtension);
            videoFilePath = string.Empty;

            //null check the info again
            if (videoInfo != null)
            {
                videoFilePath = Path.Combine(ExportVideoDirPath, fileBaseName + videoInfo.VideoExtension);
            }

            return(videoInfo);
        }
Esempio n. 45
0
        public List <Ship> Fill(ref SquareStates[,] squares, int size)
        {
            int attemptCount = 0;
            var random       = new Random();
            int maxValue     = size;
            var ships        = new List <Ship>();

            foreach (var ship in _ships?.OrderByDescending(x => x.Size))
            {
                for (int i = 0; i < ship.Count; i++)
                {
                    while (attemptCount++ < maxAttempts)
                    {
                        int x = random.Next(maxValue);
                        int y = random.Next(maxValue);

                        bool isPlace = IsPlaceForVerticalShip(squares, maxValue - 1, x, y, ship.Size);

                        if (isPlace)
                        {
                            var coordinates = PlaceShipVertical(ref squares, x, y, ship.Size);
                            ships.Add(new Ship(coordinates));

                            break;
                        }
                    }

                    if (attemptCount > maxAttempts)
                    {
                        throw new FailedToFillGridWithShipsException($"{nameof(ShipsVerticalFiller)} max attempts: {maxAttempts} reached");
                    }
                    else
                    {
                        attemptCount = 0;
                    }
                }
            }

            return(ships);
        }
        public static async Task <IPackageSearchMetadata> GetLatestPackageMetadataAsync(
            this SourceRepository sourceRepository, string packageId, bool includePrerelease, CancellationToken cancellationToken)
        {
            var metadataResource = await sourceRepository.GetResourceAsync <PackageMetadataResource>(cancellationToken);

            IEnumerable <IPackageSearchMetadata> packages = null;

            if (metadataResource != null)
            {
                packages = await metadataResource.GetMetadataAsync(
                    packageId,
                    includePrerelease,
                    false,
                    Logging.NullLogger.Instance,
                    cancellationToken);
            }

            var highest = packages?
                          .OrderByDescending(e => e.Identity.Version, VersionComparer.VersionRelease)
                          .FirstOrDefault();

            return(highest?.WithVersions(ToVersionInfo(packages, includePrerelease)));
        }
Esempio n. 47
0
 /// <summary>
 /// Create a tournament result with all entries.
 /// </summary>
 /// <param name="entries">The entries for each user that
 /// in the tournament.</param>
 public TournamentResult(DateTime date, IEnumerable <TournamentEntry> entries)
 {
     Date    = date;
     Entries = entries?.OrderByDescending(x => x.Points).ToList();
 }
Esempio n. 48
0
 /// <summary>
 /// Create a tournament result with all entries.
 /// </summary>
 /// <param name="entries">The entries for each user that participated
 /// in the tournament.</param>
 public TournamentResult(IEnumerable <TournamentEntry> entries)
 {
     Entries = entries?.OrderByDescending(x => x.Points).ToList();
 }
Esempio n. 49
0
        public async Task Run(CommandEventArgs e)
        {
            if (!_context.IsInitialized)
            {
                await e.Channel.SendMessage($"**The data is loading but is not ready yet...**");

                return;
            }

            var take = 25;

            //var args = CommandHelper.ParseArgs(e, new { Dead = false, Missing = false, Uploaded = false, Unavailable = false, Skip = 0 }, x =>
            //    x.For(y => y.Dead, flag: true)
            //    .For(y => y.Missing, flag: true)
            //    .For(y => y.Uploaded, flag: true)
            //    .For(y => y.Unavailable, flag: true)
            //    .For(y => y.Skip, defaultValue: 0));

            var args = CommandHelper.ParseArgs(e, new { Uploaded = false, Skip = 0 }, x =>
                                               x.For(y => y.Uploaded, flag: true)
                                               .For(y => y.Skip, defaultValue: 0));

            if (args == null || args.Skip < 0)
            {
                await e.Channel.SendMessage(string.Join(Environment.NewLine, new string[] {
                    $"**My logic circuits cannot process this command! I am just a bot after all... :(**",
                    !string.IsNullOrWhiteSpace(SyntaxHelp) ? $"Help me by following this syntax: **!{Name}** {SyntaxHelp}" : null
                }.Where(x => x != null)));

                return;
            }

            var player = await CommandHelper.GetCurrentPlayerOrSendErrorMessage(e, _databaseContextFactory, _context);

            if (player == null)
            {
                return;
            }

            //if(player.TribeId == null && args.Dead)
            //{
            //    //dead creatures can only be found using tribe log
            //    await e.Channel.SendMessage($"<@{e.User.Id}>, You have to be in a tribe to find dead dinos!");
            //    return;
            //}

            var nextUpdate       = _context.ApproxTimeUntilNextUpdate;
            var nextUpdateTmp    = nextUpdate?.ToStringCustom();
            var nextUpdateString = (nextUpdate.HasValue ? (!string.IsNullOrWhiteSpace(nextUpdateTmp) ? $", next update in ~{nextUpdateTmp}" : ", waiting for new update ...") : "");
            var lastUpdate       = _context.LastUpdate;
            var lastUpdateString = lastUpdate.ToStringWithRelativeDay();

            //if (!(args.Dead || args.Missing || args.Unavailable))
            //{
            IEnumerable <Creature> filtered = null;

            if (args.Uploaded)
            {
                filtered = _context.Cluster?.Creatures.Where(x => (x.PlayerId.HasValue && x.PlayerId.Value == player.Id) || (x.Team.HasValue && x.Team.Value == player.TribeId));
            }
            else
            {
                filtered = _context.CreaturesNoRaft?.Where(x => (x.PlayerId.HasValue && x.PlayerId.Value == player.Id) || (x.Team.HasValue && x.Team.Value == player.TribeId));
            }

            var dinos = filtered?.OrderByDescending(x => x.FullLevel ?? x.BaseLevel).ThenByDescending(x => x.Experience ?? decimal.MinValue).Skip(args.Skip).Take(take).ToArray();
            var count = filtered?.Count() ?? 0;

            if (args.Skip > 0 && args.Skip >= count)
            {
                await e.Channel.SendMessage($"<@{e.User.Id}>, you asked me to skip more dinos than you have!");

                return;
            }
            else if (dinos == null || dinos.Length <= 0)
            {
                await e.Channel.SendMessage($"<@{e.User.Id}>, it appears you do not have any" + (args.Uploaded ? " uploaded" : "") + " dinos... :(");

                return;
            }

            var sb = new StringBuilder();

            sb.Append($"**My records show you have {count:N0}" + (args.Uploaded ? " uploaded" : "") + " dinos");
            if (count > 10)
            {
                sb.Append($" (showing {args.Skip + 1}-{args.Skip + dinos.Length})");
            }
            sb.AppendLine($"** (updated {lastUpdateString}{nextUpdateString})");

            //todo: cluster does not appear to have species name which makes it a bit hard to present which dinos are in the cluster
            //Dictionary<long, string> species = new Dictionary<long, string>();
            //if (args.Uploaded)
            //{
            //    var ids = dinos.Where(x => string.IsNullOrWhiteSpace(x.SpeciesClass)).Select(x => x.Id).ToArray();
            //    if (ids.Length > 0)
            //    {
            //        using (var db = _databaseContextFactory.Create())
            //        {
            //            foreach (var item in db.TamedCreatureLogEntries.Where(x => ids.Contains(x.Id)).Select(x => new { id = x.Id, species = x.SpeciesClass }).ToArray())
            //            {
            //                species.Add(item.id, ArkSpeciesAliases.Instance.GetAliases(item.species)?.FirstOrDefault() ?? item.species);
            //            }
            //        }
            //    }
            //}

            foreach (var x in dinos)
            {
                //todo: cluster does not appear to have species name which makes it a bit hard to present which dinos are in the cluster
                if (args.Uploaded)
                {
                    var primary   = x.Name;
                    var secondary = x.SpeciesName;     // ?? (species.ContainsKey(x.Id) ? species[x.Id] : null);
                    if (string.IsNullOrWhiteSpace(primary))
                    {
                        primary   = secondary ?? x.Id.ToString();
                        secondary = null;
                    }
                    sb.AppendLine($"● **{primary}**" + (secondary != null ? $", ***{secondary}***" : "") + $" (lvl ***{x.FullLevel ?? x.BaseLevel}***)");
                }
                else
                {
                    sb.AppendLine($"● {(!string.IsNullOrWhiteSpace(x.Name) ? $"**{x.Name}**, ***{x.SpeciesName}***" : $"**{x.SpeciesName}**")} (lvl ***{x.FullLevel ?? x.BaseLevel}***)");
                }
            }
Esempio n. 50
0
 public static IPlayer GetPlayerForRole(this IEnumerable <IPlayer> players, IRole role, bool aliveOnly = true, IPlayer exceptPlayer = null)
 { // if aliveOnly is false, in case of multiple same roles, this will return the first alive one, or, if no alive one, the one who died the most recently
     return(players?.OrderByDescending(x => x.TimeDied).FirstOrDefault(x => x.PlayerRole == role && (!aliveOnly || !x.IsDead) && x.Id != exceptPlayer?.Id));
 }
Esempio n. 51
0
 static public T BestRead <T>(
     this IEnumerable <T> SetRead,
     Func <T, MemoryStruct.IUIElement> GetUIElementFromRead)
     where T : class =>
 SetRead?.OrderByDescending(Read => MemoryStruct.Extension.EnumerateReferencedUIElementTransitive(
                                GetUIElementFromRead?.Invoke(Read))?.Count() ?? -1)?.FirstOrDefault();
Esempio n. 52
0
 /// <summary>
 /// if aliveOnly is false, in case of multiple same roles, this will return the first alive one, or, if no alive one, the one who died the most recently
 /// </summary>
 public static IPlayer GetPlayerForRole(this IEnumerable <IPlayer> players, IRole role, bool aliveOnly = true, IPlayer exceptPlayer = null)
 {
     return(players?.OrderByDescending(x => x.TimeDied).FirstOrDefault(x => x.PlayerRole == role && (!aliveOnly || !x.IsDead) && x.Id != exceptPlayer?.Id));
 }
 public static TResult MostReliableResult <TResult>(this IEnumerable <TResult> results) where TResult : BaseResultModel
 => results?.OrderByDescending(result => result.Confidence).FirstOrDefault();
Esempio n. 54
0
 public static Card[] SortByFace(this IEnumerable <Card> cards)
 {
     return(cards?.OrderByDescending(_ => _.Face).ThenByDescending(_ => _.Suit).ToArray());
 }
Esempio n. 55
0
 static public T Grööste <T>(
     this IEnumerable <T> source)
     where T : class, IUIElement =>
 source?.OrderByDescending(element => element.Region.Area())?.FirstOrDefault();
Esempio n. 56
0
 public IEnumerable <INumberInfo> SortMostProbableNumberInfos(IEnumerable <INumberInfo> numberInfos)
 {
     return(numberInfos?.OrderByDescending(numberInfo => numberInfo.TotalTimes));
 }
Esempio n. 57
0
 static public IEnumerable <NodeT> OrderByRegionSizeDescending <NodeT>(this IEnumerable <NodeT> seq)
     where NodeT : GbsAstInfo => seq?.OrderByDescending(node => node?.Grööse?.Betraag ?? -1);
Esempio n. 58
0
 static public T LargestNodeInSubtree <T>(
     this IEnumerable <T> source)
     where T : GbsAstInfo =>
 source?.OrderByDescending(element => (element.GrööseA * element.GrööseB) ?? int.MinValue)?.FirstOrDefault();
Esempio n. 59
0
 public List <T> Sort <T>(IEnumerable <T> list) where T : ResourceBase
 {
     return(list?.OrderByDescending(team => team.Name).ToList());
 }
Esempio n. 60
0
 public static MonitorStatus GetWorstStatus(this IEnumerable <MonitorStatus> ims) => ims?.OrderByDescending(i => i).FirstOrDefault() ?? MonitorStatus.Unknown;