private Player GetClosestBy(IEnumerable<Player> queue) { var sorted = queue.OrderBy(q => GetDistanceToGoalSquared(q.Position)).ToList(); return queue .OrderBy(q => GetDistanceToGoalSquared(q.Position)) .FirstOrDefault(); }
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)); } }
//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; } }
public static IEnumerable<Country> OrderAscending(IEnumerable<Country> countries, Culture culture) { switch (culture) { case Culture.Ru: return countries.OrderBy(x => x.Translation.Ru); default: return countries.OrderBy(x => x.Translation.En); } }
private IEnumerable<SourceModel> FilterModel(IEnumerable<SourceModel> model) { var ret = model; var order = _content.Filter.OrderBy; if (order == SourceFilterModel.Order.Alphabetical) ret = model.OrderBy(x => x.Name); else if (order == SourceFilterModel.Order.FoldersThenFiles) ret = model.OrderBy(x => x.Type).ThenBy(x => x.Name); return _content.Filter.Ascending ? ret : ret.Reverse(); }
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); }
private static string[] Order(IEnumerable<string> fileSystemEntries) { try { // take in account that "2-someMigration" should go before "11-someOtherMigration" return fileSystemEntries.OrderBy(x => MigrationManager.GetMigrationId(Path.GetFileNameWithoutExtension(x))).ToArray(); } catch (FormatException) { return fileSystemEntries.OrderBy(x => x).ToArray(); } }
public static double Median(IEnumerable<double> myNumbers) { if (myNumbers.Count() == 0) throw new InvalidOperationException("Invalid count of numbers... must be greater that zero!"); if (myNumbers.Count() % 2 == 0) { return myNumbers.OrderBy(_ => _).Skip(myNumbers.Count() / 2 - 1).Take(2).Sum() / 2; } else { return myNumbers.OrderBy(_ => _).ElementAt((int)Math.Floor((decimal)(myNumbers.Count() / 2))); } }
public void LoadWidgets(IEnumerable<Widget> widgetModels, Control placeholder, TemplateControl page) { if (placeholder == null) { return; } if (page == null) { return; } if (widgetModels == null) { return; } var groups = widgetModels.OrderBy(x => x.RowNumber).ThenBy(x => x.ColumnNumber).GroupBy(x => new {x.RowNumber}); foreach (var group in groups) { foreach (Widget item in group) { using (MixERPWidgetBase widget = page.LoadControl(item.WidgetSource) as MixERPWidgetBase) { if (widget != null) { placeholder.Controls.Add(widget); widget.OnControlLoad(widget, new EventArgs()); } } } } }
public static bool Validate(IEnumerable<AlarmDisplayRange> alarmDisplayOptions) {//This should be refactored to make use of System.ComponentModel.DataAnnotations int lastUpperLimit = -1; foreach (var x in alarmDisplayOptions.OrderBy(x=>x.LowerLimit)) { //Validate Limits if(x.LowerLimit != lastUpperLimit+1)//Validate LowerLimit { return false; } if(x.UpperLimit< x.LowerLimit) { return false; } lastUpperLimit = x.UpperLimit; //Validate color (This one is most important because it could be an arbitrary string) if(x.Color == null) { return false; } if (x.Color.Length > 0 && !HexColorRegex.IsMatch(x.Color))//if a string is present by not a color { return false; } } return true; }
private Queue<Message> SetMessageOrder(IEnumerable<Message> unorderedMessages) { var messages = new Queue<Message>( unorderedMessages.OrderBy(x => x.MessengerOrderId)); return messages; }
public void Init <TKey>(IEnumerable <TSource> source, Func <TSource, TKey> keySelector, int defaultPage = 1, int maxSize = 10) { if (keySelector != null) { Source = source?.OrderBy(keySelector).ToList(); } else { Source = source?.ToList(); } Source = Source ?? new List <TSource>(); MaxSize = maxSize; Total = Source.Count; TotalPage = Convert.ToInt32(Math.Ceiling(Total * 1.0 / MaxSize)); if (TotalPage > 0) { if (defaultPage == 1) { FirstPage(); } else { LinkPage(defaultPage); } } }
public IEnumerable<PromotionMatch> MatchApplicablePromotions(PriceCalculationContext context, IEnumerable<Promotion> candidatePromotions) { var matches = new List<PromotionMatch>(); // Lower priority promotions check first candidatePromotions = candidatePromotions.OrderBy(x => x.Priority).ThenBy(x => x.Id); foreach (var promotion in candidatePromotions) { var match = TryMatchPromotion(promotion, context); if (match != null) { matches.Add(match); } } if (matches.Count > 0) { // Higher priority check first matches.Reverse(); CheckOverlappingUsage(matches); } return matches; }
public Level(string name, int rows, int columns, IEnumerable <int> on) : this(name, rows, columns) { var onArray = on?.OrderBy(t => t).ToArray() ?? throw new ArgumentException(nameof(on)); if (onArray.Any(o => o < 0)) { throw new ArgumentOutOfRangeException(nameof(on)); } if (onArray.Any(o => o > columns * rows)) { throw new ArgumentOutOfRangeException(nameof(on)); } var onMatrix = new SwitchState[rows, columns]; foreach (var item in onArray) { onMatrix[item % columns, item / columns] = SwitchState.On; } Matrix = onMatrix; }
/// <summary> /// Calculates the median of the given numbers. /// </summary> /// <param name="numbers">The numbers whose median is to be calculated.</param> /// <returns>The median of the given numbers.</returns> /// <exception cref="System.ArgumentNullException"> /// The specified collection must not be null. /// </exception> /// <exception cref="System.InvalidOperationException"> /// The arguments must not be empty. /// </exception> public static double Median(IEnumerable<double> numbers) { if (numbers == null) { throw ArgumentNullException; } if (!numbers.Any()) { throw EmptyNumbersCollectionException; } List<double> sortedNumbers = numbers.OrderBy(number => number).ToList(); double median = 0; if (sortedNumbers.Count % 2 == 0) { double lowerMedian = sortedNumbers[sortedNumbers.Count / 2 - 1]; double upperMedian = sortedNumbers[sortedNumbers.Count / 2]; median = ArithmeticMeanCalculator.ArithmeticMean(lowerMedian, upperMedian); } else { median = sortedNumbers[sortedNumbers.Count / 2]; } return median; }
internal EffectParameterUpdaterDefinition(IEnumerable<ParameterKey> keys, IEnumerable<ParameterDependency> dependencies) { SortedKeys = keys.OrderBy(x => x.HashCode).ToArray(); SortedKeyHashes = SortedKeys.Select(x => x.HashCode).ToArray(); // Sort dependencies dependencies = BuildDependencies(dependencies).ToArray(); // Build dependencies (with indices instead of keys) var dependenciesIndex = new List<ParameterDependencyIndex>(); foreach (var dependency in dependencies) { var destinationIndex = Array.IndexOf(SortedKeys, dependency.Destination); if (destinationIndex == -1) throw new InvalidOperationException(); var sourceIndices = dependency.Sources.Select(x => Array.IndexOf(SortedKeys, x)).ToArray(); if (sourceIndices.Any(x => x == -1)) throw new InvalidOperationException(); dependenciesIndex.Add(new ParameterDependencyIndex { Destination = destinationIndex, Sources = sourceIndices, Dynamic = dependency.Dynamic, //Parameters = new ParameterCollection.InternalValueReference[dependency.Sources.Length], }); } this.Dependencies = dependenciesIndex.ToArray(); ThreadLocalDynamicValues = new ParameterCollection.InternalValue[GraphicsDevice.ThreadCount][]; for (int i = 0; i < ThreadLocalDynamicValues.Length; ++i) { ThreadLocalDynamicValues[i] = Dependencies.Select(x => ParameterCollection.CreateInternalValue(SortedKeys[x.Destination])).ToArray(); } }
private static string GetContent(IEnumerable<Notification> notifications) { return notifications .OrderBy(x => x.Date) .Aggregate(new StringBuilder(), (s, notification) => s.AppendLine(notification.Content).AppendLine().AppendLine("----------").AppendLine()) .ToString(); }
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 static void ShowIconMenu <T>(Point position, IEnumerable <Tuple <T, Bitmap> > items, Action <T> pickHandler) { List <Tuple <T, Bitmap> > itemList = items?.OrderBy(item => item.Item1.ToString()).ToList(); if (itemList == null || !itemList.Any()) { return; } ContextMenuStrip contextMenu = new ContextMenuStrip(); ToolStripDropDownClosedEventHandler contextMenuClosedEventHandler = null; ToolStripItemClickedEventHandler menuItemClickedEventHandler = null; contextMenuClosedEventHandler = (sender, e) => { contextMenu.Closed -= contextMenuClosedEventHandler; contextMenu.ItemClicked -= menuItemClickedEventHandler; }; menuItemClickedEventHandler = (sender, e) => { contextMenu.Closed -= contextMenuClosedEventHandler; contextMenu.ItemClicked -= menuItemClickedEventHandler; contextMenu.Close(); pickHandler((T)e.ClickedItem.Tag); }; contextMenu.Closed += contextMenuClosedEventHandler; contextMenu.ItemClicked += menuItemClickedEventHandler; itemList.ForEach(item => contextMenu.Items.Add(new ToolStripMenuItem(item.Item1.ToString()) { Tag = item.Item1, Image = item.Item2 })); contextMenu.Show(position); }
private void ParseEvents(IEnumerable<SDEvent> events) { foreach (var ev in events.OrderBy(o => o.Name)) { _classDiagram.EventRows.Add(new ClassDiagramRow(ev.Identifier, "Event", ev.Accessibility, ev.Name)); } }
public void LoadWidgets(IEnumerable<DefaultWidgetSetupView> widgetModels, Control placeholder, TemplateControl page) { if (placeholder == null) { return; } if (page == null) { return; } if (widgetModels == null) { return; } foreach (DefaultWidgetSetupView item in widgetModels.OrderBy(x => x.WidgetOrder)) { using (MixERPWidget widget = page.LoadControl(item.WidgetSource) as MixERPWidget) { if (widget != null) { placeholder.Controls.Add(widget); widget.OnControlLoad(widget, new EventArgs()); } } } }
internal RepoConfig( IEnumerable<NuGetPackage> fixedPackages, IEnumerable<string> toolsetPackages, IEnumerable<Regex> nuspecExcludes, IEnumerable<Regex> projectJsonExcludes, GenerateData? msbuildGenerateData) { Debug.Assert(toolsetPackages.Distinct().Count() == toolsetPackages.Count()); MSBuildGenerateData = msbuildGenerateData; FixedPackages = fixedPackages.OrderBy(x => x.Name).ToImmutableArray(); NuSpecExcludes = nuspecExcludes.ToImmutableArray(); ProjectJsonExcludes = projectJsonExcludes.ToImmutableArray(); ToolsetPackages = toolsetPackages.OrderBy(x => x).ToImmutableArray(); var map = new Dictionary<string, List<string>>(); foreach (var nugetRef in fixedPackages) { List<string> list; if (!map.TryGetValue(nugetRef.Name, out list)) { list = new List<string>(capacity: 1); map[nugetRef.Name] = list; } list.Add(nugetRef.Version); } }
private static IEnumerable<TimeSpan> GetDelta(IEnumerable<DateTime> target) { var orderTarget = target.OrderBy(x => x.ToUniversalTime()); var deltas = orderTarget.Zip(orderTarget.Skip(1), (current, next) => next - current); return deltas; }
/// <inheritdoc /> public IEnumerable<Offer> GetTheBestAvailableOffersFromLenders(IEnumerable<Lender> lenders, decimal requestedLoadAmount) { //order the lenders by best rate lenders = lenders.OrderBy(x => x.Rate).ToList(); //container to store offers var offers = new List<Offer>(); //loop through the lenders foreach (var lender in lenders) { //get the total already offered. var totalOffered = offers.Sum(item => item.Amount); //if the total offered is less than the requested amount if (totalOffered < requestedLoadAmount) { //add a new offer which will be either the full amount the lender has available or //the amount that the system needs to make up the requested loan amount. offers.Add(new Offer(Math.Min(lender.Available, requestedLoadAmount - totalOffered), lender.Rate)); } //we have enough offers else { //end the loop break; } } //return the offers to the caller. return offers; }
/// <summary> /// Calculates the truncated mean of the specified collection of numbers /// regarding the specified percentage of elements to be discarded. /// </summary> /// <param name="numbers">The numbers whose truncated mean is to be calculated.</param> /// <param name="percentageToDiscard">The percentage of elements that /// are to be discarded at both sides of the collection in each case.</param> /// <returns>The truncated mean of the specified collection of numbers.</returns> /// <exception cref="System.InvalidOperationException"> /// The specified collection must not be empty. /// </exception> /// <exception cref="System.ArgumentNullException"> /// The specified collection must not be null. /// </exception> public static double TruncatedMean(IEnumerable<double> numbers, double percentageToDiscard) { if (numbers == null) { throw ArgumentNullException; } if (!numbers.Any()) { throw EmptyNumbersCollectionException; } // The percentage to discard needs to be greater than 0 and smaller than 50% as // it makes no sense to both discard nothing and discard all (50% on both sides). if (percentageToDiscard <= 0 || percentageToDiscard >= 0.5) { throw new ArgumentException( "percentageToDiscard must be greater than 0 and smaller than 0.5!"); } var orderedNumbers = numbers.OrderBy(n => n); IEnumerable<double> truncatedNumbers = TruncationHelper<double>.Truncate(orderedNumbers, percentageToDiscard); double truncatedMean = truncatedNumbers.ArithmeticMean(); return truncatedMean; }
public IEnumerable<IStory> Solve(int capacity, IEnumerable<IStory> candidates) { if (capacity < 0) throw new ArgumentException("Argument must be greater than zero", "capacity"); if (candidates == null) throw new ArgumentNullException("candidates"); var candidateList = new LinkedList<IStory>(candidates.OrderBy(x => x.Priority).ThenByDescending(x => x.Points)); int capacityLeft = capacity; bool candidateFound = true; List<IStory> solution = new List<IStory>(); while (capacityLeft > 0 && candidateFound) { candidateFound = false; foreach (var candidate in candidateList) { if (capacityLeft >= candidate.Points) { solution.Add(candidate); capacityLeft -= candidate.Points; candidateList.Remove(candidate); candidateFound = true; break; } } } return solution; }
public override string Visit(IEnumerable<Item> items, string current) { if(current.IndexOf(TOKEN) < 0) return current; return current.Replace(TOKEN, runFilter<ProphecyFilter>(items.OrderBy(i => i.H))); }
public PackageDependencyProcessor(IEnumerable<IPackageInfo> packages) { _packages = packages; _graph = new DependencyGraph<IPackageInfo>(pak => pak.Name, pak => pak.GetDependencies().Select(x => x.Name)); _packages.OrderBy(p => p.Name).Each(p => _graph.RegisterItem(p)); }
public Repository(string name, string description, long forkCount, string ownerLogin, string ownerAvatarUrl, long issuesCount, string url, bool isFork, DateTimeOffset dataDownloadedAt, bool?isFavorite = null, IList <DailyViewsModel>?views = null, IList <DailyClonesModel>?clones = null, IEnumerable <DateTimeOffset>?starredAt = null) { IsFavorite = isFavorite; DataDownloadedAt = dataDownloadedAt; StarredAt = (starredAt?.OrderBy(x => x) ?? Enumerable.Empty <DateTimeOffset>()).ToList(); StarCount = StarredAt.Count; Name = name; Description = description; ForkCount = forkCount; OwnerLogin = ownerLogin; OwnerAvatarUrl = ownerAvatarUrl; IssuesCount = issuesCount; Url = url; IsFork = isFork; if (views != null && clones != null) { AddMissingDates(views, clones); } DailyViewsList = (views ?? Enumerable.Empty <DailyViewsModel>()).ToList(); DailyClonesList = (clones ?? Enumerable.Empty <DailyClonesModel>()).ToList(); TotalViews = DailyViewsList.Sum(x => x.TotalViews); TotalUniqueViews = DailyViewsList.Sum(x => x.TotalUniqueViews); TotalClones = DailyClonesList.Sum(x => x.TotalClones); TotalUniqueClones = DailyClonesList.Sum(x => x.TotalUniqueClones); IsTrending = (DailyViewsList.IsTrending() ?? false) || (DailyClonesList.IsTrending() ?? false); }
public Assembly(string name, IEnumerable<Concern> concerns) : base(concerns.Cast<SpecificationContainer>()) { _name = name; _concerns = concerns.OrderBy(x => x.Name).ToList(); _totalConerns = concerns.Count(); _totalContexts = concerns.Sum(x => x.TotalContexts); }
internal void GenerateLibraryProjectFile(CodeGeneratorOptions options, IEnumerable <string> enumFiles, string path = null) { if (path == null) { var name = Assembly ?? "GeneratedFiles"; int idx = name.IndexOf(','); name = idx < 0 ? name : name.Substring(0, idx); path = Path.Combine(csdir, name + ".projitems"); } var msbuild = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003"); var compile = msbuild + "Compile"; var project = new XElement( msbuild + "Project", ToDefineConstants(options, msbuild), new XComment(" Classes "), new XElement( msbuild + "ItemGroup", GeneratedFiles .OrderBy(f => f, StringComparer.OrdinalIgnoreCase) .Select(f => ToCompileElement(compile, f))), new XComment(" Enums "), new XElement( msbuild + "ItemGroup", enumFiles ?.OrderBy(f => f, StringComparer.OrdinalIgnoreCase) ?.Select(f => ToCompileElement(compile, f)))); project.Save(path); }
/// <summary> /// Imports the specified set of authority tokens. /// </summary> /// <param name="tokenDefs"></param> /// <param name="addToGroups"></param> /// <param name="context"></param> /// <returns></returns> public IList<AuthorityToken> Import(IEnumerable<AuthorityTokenDefinition> tokenDefs, IList<string> addToGroups, IUpdateContext context) { // first load all the existing tokens into memory // there should not be that many tokens ( < 500), so this should not be a problem var broker = context.GetBroker<IAuthorityTokenBroker>(); var existingTokens = broker.FindAll(); // if there are groups to add to, load the groups var groups = addToGroups != null && addToGroups.Count > 0 ? LoadGroups(addToGroups, context) : new List<AuthorityGroup>(); // order the input such that the renames are processed first // otherwise there may be a corner case where a newly imported token is immediately renamed tokenDefs = tokenDefs.OrderBy(t => t.FormerIdentities.Length > 0); foreach (var tokenDef in tokenDefs) { var token = ProcessToken(tokenDef, existingTokens, context); // add to groups CollectionUtils.ForEach(groups, g => g.AuthorityTokens.Add(token)); } return existingTokens; }
public IEnumerable <Employee> ProcessData(IEnumerable <Employee> employees) { IEnumerable <Employee> processedEmployees = employees; try { if (!string.IsNullOrWhiteSpace(_filterCondition)) { processedEmployees = employees?.Where(_filterCondition); } } catch (Exception) { Console.Out.WriteLine("Error: Couldn't filter employees."); } try { if (_propagation > 0 && !string.IsNullOrWhiteSpace(_orderingCondition)) { processedEmployees = processedEmployees?.OrderBy(_orderingCondition); } } catch (Exception) { Console.Out.WriteLine("Error: Couldn't sort employees."); } return(processedEmployees); }
public static MarketPrices ReadData(IEnumerable<string> symbols, string dataItem, TimeSeries timeSeries) { List<string> symbolsList = symbols.OrderBy(x => x).ToList(); MarketPrices allData2 = For(symbolsList, dataItem, timeSeries); return allData2; }
private void ParseFields(IEnumerable<SDField> fields) { foreach (var field in fields.OrderBy(o => o.Name)) { _classDiagram.FieldRows.Add(new ClassDiagramRow(field.Identifier, "Field", field.Accessibility, field.Name)); } }
private void ParseMethods(IEnumerable<SDMethod> methods) { foreach (var method in methods.OrderBy(o => o.Name)) { _classDiagram.MethodRows.Add(new ClassDiagramRow(method.Identifier, "Method", method.Accessibility, method.Name)); } }
public static IOrderedEnumerable <T> OrderBy <T, TKey>( IEnumerable <T> enumerable, Func <T, TKey> keySelector, bool ascending ) { return(ascending ? enumerable?.OrderBy(keySelector) : enumerable?.OrderByDescending(keySelector)); }
/// <summary> /// Initializes a new instance of the <see cref="RazorSourceUpdater"/> class. /// </summary> /// <param name="analyzers">Analyzers to use when analyzing source code in the Razor documents.</param> /// <param name="codeFixProviders">Code fix providers to use when fixing diagnostics found in the Razor documents.</param> /// <param name="textMatcher">The text matching service to use for correlating old sections of text in Razor documents with updated texts.</param> /// <param name="textReplacer">The text replacing service to use for updating replaced texts in the Razor documents.</param> /// <param name="logger">An ILogger to log diagnostics.</param> public RazorSourceUpdater(IEnumerable <DiagnosticAnalyzer> analyzers, IEnumerable <CodeFixProvider> codeFixProviders, ITextMatcher textMatcher, ITextReplacer textReplacer, ILogger <RazorSourceUpdater> logger) { _analyzers = analyzers?.OrderBy(a => a.SupportedDiagnostics.First().Id) ?? throw new ArgumentNullException(nameof(analyzers)); _codeFixProviders = codeFixProviders?.OrderBy(c => c.FixableDiagnosticIds.First()) ?? throw new ArgumentNullException(nameof(codeFixProviders)); _textMatcher = textMatcher ?? throw new ArgumentNullException(nameof(textMatcher)); _textReplacer = textReplacer ?? throw new ArgumentNullException(nameof(textReplacer)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); }
public Payment GetEarliestPayment(IEnumerable <Payment> payments) { return(payments? .OrderBy(p => p.AcademicYear) .ThenBy(p => p.DeliveryPeriod) .ThenBy(p => p.CollectionPeriod) .FirstOrDefault()); }
public EnumerableDataReader(IEnumerable <TResult> items, IEnumerable <PropertyMapping> propertyMappings) { _items = items ?? throw new ArgumentNullException(nameof(items)); _propertyMappings = propertyMappings?.OrderBy(x => x.Source.Ordinal).ToArray() ?? throw new ArgumentNullException(nameof(propertyMappings)); _ordinalToPropertyMappings = _propertyMappings.ToDictionary(x => x.Source.Ordinal); _nameToOrdinalMappings = _propertyMappings.ToDictionary(x => x.Source.Property.Name, x => x.Source.Ordinal); }
public Account(int id, string number, string name, IEnumerable <Balance> balances, IEnumerable <Position> positions) { Id = id; Number = number ?? throw new ArgumentNullException(nameof(name)); Name = name ?? throw new ArgumentNullException(nameof(name)); Balances = balances?.OrderBy(b => b.Currency.Code).ToArray() ?? throw new ArgumentNullException(nameof(balances)); Positions = positions?.OrderBy(p => p.Symbol.Name).ToArray() ?? throw new ArgumentNullException(nameof(positions));; }
public static int GetSequenceHashOrdered <T>(this IEnumerable <T> items) { var result = items? .OrderBy(s => s)? .GetSequenceHash() ?? 0; return(result); }
public static IEnumerable <T> OrderByCenterDistanceToPoint <T>(this IEnumerable <T> sequence, Vektor2DInt point) where T : IUIElement { return(sequence?.OrderBy(delegate(T element) { Vektor2DInt value = point; Vektor2DInt?subtrahend = (element != null) ? element.RegionCenter() : null; return (value - subtrahend)?.LengthSquared() ?? long.MaxValue; })); }
public PaymentOrderViewModel(IEnumerable <PaymentOrderItem> items) { PaymentOrderItems = items; ProviderPaymentOrder = PaymentOrderItems? .OrderBy(o => o.Priority) .Select(p => p.ProviderId.ToString()) .ToArray() ?? default; }
public static IEnumerable <ParameterABI> Ordered(this IEnumerable <ParameterABI> parameters) { if (parameters == null) { return(new ParameterABI[0]); } return(parameters?.OrderBy(p => p.Order)); }
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; }
protected EnumerableDataReaderBase(IEnumerable <PropertyMapping> propertyMappings) { _propertyMappings = propertyMappings?.OrderBy(x => x.Source.Ordinal).ToArray() ?? throw new ArgumentNullException(nameof(propertyMappings)); // Map the source entity's positional ordinals to the source/destination property mapping. _ordinalToPropertyMappings = _propertyMappings.ToDictionary(x => x.Source.Ordinal); // Map the destination table's ordinals to the source/destination property mapping, // using the source property's name as the key. _nameToOrdinalMappings = _propertyMappings.ToDictionary(x => x.Source.Property.Name, x => x.Destination.ColumnOrdinal); }
public ResolvingRequestMiddleware( IEnumerable <ISiteRouteResolver> routeResolvers, IEnumerable <ISiteRouteGlobalResolver> globalResolvers, ISiteRequestAccessor siteRequest, IMemoryCache memoryCache) { _routeResolvers = routeResolvers; _globalResolvers = globalResolvers?.OrderBy(a => a.Order); _siteRequest = siteRequest; _memoryCache = memoryCache; }
public static void SetGenericModDependancies(this IniFileSection section, string key, [CanBeNull] IEnumerable <string> values) { var v = values?.OrderBy(x => x).Select(x => $"\"{x}\"").JoinToString(); if (string.IsNullOrWhiteSpace(v)) { section.Remove(key); } else { section.Set(key, v); } }
public static void ShowMenu <T1, T2>(Point position, IEnumerable <T1> rootItems, IEnumerable <T2> items, Action <T1, T2> pickHandler) { IEnumerable <T1> rootItemList = rootItems as IList <T1> ?? rootItems?.ToList(); if (rootItemList == null || !rootItemList.Any()) { return; } List <T2> itemList = items?.OrderBy(item => item.ToString()).ToList(); if (itemList == null || !itemList.Any()) { return; } ContextMenuStrip contextMenu = new ContextMenuStrip(); foreach (T1 rootItem in rootItemList) { ToolStripMenuItem rootMenuItem = new ToolStripMenuItem(rootItem.ToString()) { Tag = rootItem }; contextMenu.Items.Add(rootMenuItem); itemList.ForEach(item => rootMenuItem.DropDownItems.Add(new ToolStripMenuItem(item.ToString()) { Tag = new Tuple <T1, T2>(rootItem, item) })); } ToolStripDropDownClosedEventHandler contextMenuClosedEventHandler = null; ToolStripItemClickedEventHandler menuItemClickedEventHandler = null; contextMenuClosedEventHandler = (sender, e) => { contextMenu.Closed -= contextMenuClosedEventHandler; contextMenu.Items.Cast <ToolStripMenuItem>().ToList().ForEach(x => x.DropDownItemClicked -= menuItemClickedEventHandler); }; menuItemClickedEventHandler = (sender, e) => { contextMenu.Closed -= contextMenuClosedEventHandler; contextMenu.Items.Cast <ToolStripMenuItem>().ToList().ForEach(x => x.DropDownItemClicked -= menuItemClickedEventHandler); contextMenu.Close(); Tuple <T1, T2> tag = (Tuple <T1, T2>)e.ClickedItem.Tag; pickHandler(tag.Item1, tag.Item2); }; contextMenu.Closed += contextMenuClosedEventHandler; contextMenu.Items.Cast <ToolStripMenuItem>().ToList().ForEach(x => x.DropDownItemClicked += menuItemClickedEventHandler); contextMenu.Show(position); }
/// <summary> /// Initializes a new instance of the <see cref="RazorSourceUpdater"/> class. /// </summary> /// <param name="analyzers">Analyzers to use when analyzing source code in the Razor documents.</param> /// <param name="codeFixProviders">Code fix providers to use when fixing diagnostics found in the Razor documents.</param> /// <param name="additionalTexts">Additional documents that should be included in analysis. This will typically be additional texts used to configure analyzer behavior.</param> /// <param name="textMatcher">The text matching service to use for correlating old sections of text in Razor documents with updated texts.</param> /// <param name="textReplacer">The text replacing service to use for updating replaced texts in the Razor documents.</param> /// <param name="logger">An ILogger to log diagnostics.</param> public RazorSourceUpdater(IEnumerable <DiagnosticAnalyzer> analyzers, IEnumerable <CodeFixProvider> codeFixProviders, IEnumerable <AdditionalText> additionalTexts, ITextMatcher textMatcher, IMappedTextReplacer textReplacer, ILogger <RazorSourceUpdater> logger) { if (additionalTexts is null) { throw new ArgumentNullException(nameof(additionalTexts)); } _analyzers = analyzers?.OrderBy(a => a.SupportedDiagnostics.First().Id) ?? throw new ArgumentNullException(nameof(analyzers)); _codeFixProviders = codeFixProviders?.OrderBy(c => c.FixableDiagnosticIds.First()) ?? throw new ArgumentNullException(nameof(codeFixProviders)); _additionalTexts = ImmutableArray.CreateRange(additionalTexts); _textMatcher = textMatcher ?? throw new ArgumentNullException(nameof(textMatcher)); _textReplacer = textReplacer ?? throw new ArgumentNullException(nameof(textReplacer)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); }
public static void ShowMultiSelectMenu <T>(Point position, IEnumerable <Tuple <T, bool> > items, Action <List <T> > pickHandler) { List <Tuple <T, bool> > itemList = items?.OrderBy(item => item.Item1.ToString()).ToList(); if (itemList == null || !itemList.Any()) { return; } bool anyItemClicked = false; ContextMenuStrip contextMenu = new ContextMenuStrip(); ToolStripDropDownClosedEventHandler contextMenuClosedEventHandler = null; ToolStripDropDownClosingEventHandler contextMenuClosingEventHandler = null; ToolStripItemClickedEventHandler menuItemClickedEventHandler = null; contextMenuClosedEventHandler = (sender, e) => { contextMenu.Closed -= contextMenuClosedEventHandler; contextMenu.Closing -= contextMenuClosingEventHandler; contextMenu.ItemClicked -= menuItemClickedEventHandler; }; contextMenuClosingEventHandler = (sender, e) => { if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked) { e.Cancel = true; ((ToolStripDropDownMenu)sender).Invalidate(); } else if (anyItemClicked) { List <T> selectedItems = ((ToolStripDropDownMenu)sender).Items.Cast <ToolStripMenuItem>().Where(x => x.Checked).Select(x => (T)x.Tag).ToList(); pickHandler(selectedItems); } }; menuItemClickedEventHandler = (sender, e) => { ToolStripMenuItem clickedItem = (ToolStripMenuItem)e.ClickedItem; clickedItem.Checked = !clickedItem.Checked; anyItemClicked = true; }; contextMenu.Closed += contextMenuClosedEventHandler; contextMenu.Closing += contextMenuClosingEventHandler; contextMenu.ItemClicked += menuItemClickedEventHandler; itemList.ForEach(item => contextMenu.Items.Add(new ToolStripMenuItem(item.Item1.ToString()) { Tag = item.Item1, Checked = item.Item2 })); contextMenu.Show(position); }
/// <summary> /// Orders a Transaction Entry by Date and converts it to a Simple Transaction Entry model already having a string /// //var transactions = entries?.OrderBy(e => { return e.Date; }).ToLookup( => t.Date.Year).ToLookup(t => t.ToLookup(e => e.Date.Month)); /// </summary> /// <returns></returns> public IEnumerable <TransactionEntry> GetEntriesByDate(DateTime date) { if (date.Date == DateTime.MinValue.Date) { return(entries?.Skip(1).ToList() .ConvertAll( e => new TransactionEntry { Amount = e.Amount, ID = e.ID, Date = e.Date.ToString("o"), OpDate = e.OpDate.ToString("o"), Description = e.Description, Currency = e.Currency, Saldo = e.Saldo, Cur = e.Cur }) ?? new List <TransactionEntry>()); } return(entriesLookUp[new DateTime(date.Year, date.Month, 1)].ToList().ConvertAll( e => new TransactionEntry { Amount = e.Amount, ID = e.ID, Date = e.Date.ToString("o"), OpDate = e.OpDate.ToString("o"), Description = e.Description, Currency = e.Currency, Saldo = e.Saldo, Cur = e.Cur }) ?? new List <TransactionEntry>()); return(entries?.OrderBy(e => { return e.Date; }).ToList() .ConvertAll( (e) => { return new TransactionEntry { Amount = e.Amount, ID = e.ID, Date = e.Date.ToShortDateString(), OpDate = e.OpDate.ToShortDateString(), Description = e.Description, Currency = e.Currency, Saldo = e.Saldo, Cur = e.Cur }; }) ?? new List <TransactionEntry>()); }
private void LoadData(IEnumerable <FullEmployee> employees) { employees = employees?.OrderBy(r => r.FirstName).ToList(); Collection = employees != null ? new ObservableCollection <FullEmployee>(employees) : new ObservableCollection <FullEmployee>(); ShowNoResults = !Collection.Any(); if (ShowNoResults) { State = State.Empty; } else { State = State.None; } }
/// <summary> /// Get containers under natual ordering. /// <paramref name="flags"/> = Image | Archive means the child can be either Image or Archive. /// </summary> public static IEnumerable <ObjectInfo> GetContainers(string path, bool recurse = true) { IEnumerable <ObjectInfo> infos = null; switch (GetPathType(path)) { case FileFlags.Directory: infos = EnumerateContainers(path, recurse); break; case FileFlags.Archive: infos = new[] { new ObjectInfo(path, FileFlags.Archive) }; break; } return(infos?.OrderBy(i => i.FileSystemPath, new NativeHelpers.NaturalStringComparer())); }
private static async Task <IEnumerable <Dealer> > GetDealers(string datasetId, IEnumerable <Vehicle> vehicles) { IEnumerable <Dealer> dealers = null; await Spinner.StartAsync("Loading Dealers in Parallel...", async spinner => { var timer = Stopwatch.StartNew(); var dealerTasks = vehicles .Select(v => v.DealerId) .Distinct() .Select(dId => _svc.GetDealerAsync(datasetId, dId)); dealers = (await Task.WhenAll(dealerTasks)); timer.Stop(); spinner.Succeed($"Loaded '{dealers.Count()}' dealers ({timer.Elapsed:c})"); }); return(dealers?.OrderBy(d => d.DealerId).ToList()); }
/// <summary> /// source 排除 exceptPeriods /// <remarks>邊檢查邊回傳</remarks> /// </summary> /// <param name="source"></param> /// <param name="exceptPeriods"></param> /// <returns></returns> /// <exception cref="NotSupportedException"></exception> public static IEnumerable <DurationDto> Except(this DurationDto source, IEnumerable <DurationDto> exceptPeriods) { // 先依照起始日期排序 var exceptPeriodsByOrder = exceptPeriods?.OrderBy(p => p.Begin) .ThenBy(p => p.End) .ToArray() ?? new DurationDto[0]; var begin = source.Begin; foreach (var exceptPeriod in exceptPeriodsByOrder) { if (begin < exceptPeriod.Begin) { if (source.End >= exceptPeriod.Begin) { yield return(new DurationDto(begin, exceptPeriod.Begin)); begin = exceptPeriod.End; } } else if (begin == exceptPeriod.Begin) { begin = exceptPeriod.End; } else // begin > exceptPeriod.Begin { if (begin < exceptPeriod.End) { begin = exceptPeriod.End; } } } if (begin < source.End) { yield return(new DurationDto(begin, source.End)); } else if (begin > source.End) { // throw new NotSupportedException("結束時間早於於排除起始時間"); } }
static void Main(string[] args) { string[] lines = File.ReadAllLines("input.txt"); IEnumerable <Seat> seats = lines.Select(ParseSeating).ToList(); IEnumerable <Seat> orderedSeats = seats?.OrderBy(s => s.SeatId).ToList(); for (int i = 0; i < orderedSeats.Count() - 2; i++) { int lastSeatId = orderedSeats.ElementAt(i).SeatId; int nextSeatId = orderedSeats.ElementAt(i + 1).SeatId; if (nextSeatId - lastSeatId == 2) { Console.WriteLine($"Found candidate: {lastSeatId + 1}"); } } }
public void GetDisplayMetadata_EnumDisplayNamesAndValues_ReflectsModelType( Type type, IEnumerable <KeyValuePair <string, string> > expectedKeyValuePairs) { // Arrange var provider = new DataAnnotationsMetadataProvider(); var key = ModelMetadataIdentity.ForType(type); var attributes = new object[0]; var context = new DisplayMetadataProviderContext(key, new ModelAttributes(attributes)); // Act provider.GetDisplayMetadata(context); // Assert // OrderBy is used because the order of the results may very depending on the platform / client. Assert.Equal( expectedKeyValuePairs?.OrderBy(item => item.Key, StringComparer.Ordinal), context.DisplayMetadata.EnumDisplayNamesAndValues?.OrderBy(item => item.Key, StringComparer.Ordinal)); }