/// <summary> /// Gets the set of interactors within a given query rectangle. /// </summary> /// <param name="behaviorMaps">Behavior maps providing the interactors.</param> /// <param name="queryRect">Query rectangle in screen coordinates.</param> /// <param name="queryWindowIds">Window ID's from the query.</param> /// <returns>The interactors.</returns> public static IEnumerable<FormsInteractor> GetInteractors(IEnumerable<BehaviorMap> behaviorMaps, Rectangle queryRect, IEnumerable<string> queryWindowIds) { var windowIdArray = queryWindowIds.ToArray(); // avoid multiple traversals of the enumeration foreach (var behaviorsByForm in behaviorMaps .ToLookup<BehaviorMap, Form>(map => GetForm(map))) { var form = behaviorsByForm.Key; if (form == null) { continue; } var windowId = form.Handle.ToString(); if (!windowIdArray.Contains(windowId)) { continue; } // Find all interactors intersecting the query rectangle. // Since controls cannot extend outside the bounds of their parent controls/forms // in Windows Forms, we know that this operation will find all parent interactors // as well. foreach (var interactor in behaviorsByForm .SelectMany(map => map.GetIntersectingInteractors(queryRect))) { yield return interactor; } } }
internal static void DeleteFiles(this IFileSystem fileSystem, IEnumerable<IPackageFile> files, string rootDir) { // First get all directories that contain files var directoryLookup = files.ToLookup(p => Path.GetDirectoryName(p.Path)); // Get all directories that this package may have added var directories = from grouping in directoryLookup from directory in GetDirectories(grouping.Key) orderby directory.Length descending select directory; // Remove files from every directory foreach (var directory in directories) { var directoryFiles = directoryLookup.Contains(directory) ? directoryLookup[directory] : Enumerable.Empty<IPackageFile>(); string dirPath = Path.Combine(rootDir, directory); if (!fileSystem.DirectoryExists(dirPath)) { continue; } foreach (var file in directoryFiles) { string path = Path.Combine(rootDir, file.Path); fileSystem.DeleteFileSafe(path, file.GetStream); } // If the directory is empty then delete it if (!fileSystem.GetFilesSafe(dirPath).Any() && !fileSystem.GetDirectoriesSafe(dirPath).Any()) { fileSystem.DeleteDirectorySafe(dirPath, recursive: false); } } }
/// <summary> /// Initializes a new instance of the <see cref="AuthHeaderInfo" /> class. /// </summary> /// <param name="name">The authentication method name</param> /// <param name="rawValue">The raw authentication method values</param> /// <param name="values">The parsed authentication method values</param> /// <param name="rawValues">The raw parsed authentication method values</param> public AuthHeaderInfo(string name, string rawValue, IEnumerable<KeyValuePair<string, string>> values, IEnumerable<KeyValuePair<string, string>> rawValues) { Name = name; RawValue = rawValue; Values = values.ToLookup(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase); RawValues = rawValues.ToLookup(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase); }
public UnreadCount GetUnreadCount(IEnumerable<string> addresses, DateTime time) { var smsCount = 0; var emailCount = 0; var missedCallCount = 0; var lookUpAddressIsEmail = addresses.ToLookup(a => a.Contains("@")); if (lookUpAddressIsEmail[true].Any()) { emailCount = _emailService.GetEmailNewerThanDateTimeCount(lookUpAddressIsEmail[true], time); } if (lookUpAddressIsEmail[false].Any()) { smsCount = _smsService.GetSmsNewerThanDateTimeCount(lookUpAddressIsEmail[false], time); missedCallCount = _callService.GetMissedCallsNewerThanDateTime(lookUpAddressIsEmail[false], time); } var lastContact = GetLastContacted(lookUpAddressIsEmail); return new UnreadCount { UnreadEmailCount = emailCount, UnreadSmsCount = smsCount, MissedCallsCount = missedCallCount, SinceTime = time, LastContact = lastContact != DateTime.MinValue ? lastContact : null }; }
/// <summary> /// Creates a dictionary from collection without duplicates. /// </summary> /// <typeparam name="T">The collection type.</typeparam> /// <typeparam name="TValue">The dictionary value type.</typeparam> /// <param name="collection">The collection.</param> /// <param name="keySelector">The key selector.</param> /// <param name="elementSelector">The element selector.</param> /// <returns></returns> public static IDictionary <string, TValue> ToDictionaryIgnoreCase <T, TValue>(this IEnumerable <T> collection, Func <T, string> keySelector, Func <T, TValue> elementSelector) { return(collection? .ToLookup(keySelector, elementSelector, StringComparer.InvariantCultureIgnoreCase) .Where(x => !string.IsNullOrWhiteSpace(x.Key)) .ToDictionary(x => x.Key, x => x.First(), StringComparer.InvariantCultureIgnoreCase)); }
private Repository Map(GitRepository toMap, IEnumerable <GitCommitRef> commits = null, IEnumerable <GitPullRequest> pullRequests = null, IEnumerable <GitBranchStat> branches = null, IEnumerable <Models.AzureDevops.BuildDefinition> buildDefinitions = null, IEnumerable <Models.AzureDevops.ReleaseDefinition> releaseDefinitions = null, IEnumerable <Models.AzureDevops.ReleaseDefinition> releaseDefinitionsForRepo = null, IEnumerable <Models.AzureDevops.Release> releases = null) { var commitsRealized = commits.ToList(); var commitSummary = Map(commitsRealized ?? new List <GitCommitRef>())?.ToList(); var pullRequestSummary = Map(pullRequests ?? new List <GitPullRequest>())?.ToList(); var branchSummary = Map(branches ?? new List <GitBranchStat>(), toMap)?.ToList(); var releaseDefinitionsByBuildId = releaseDefinitions?.ToLookup(r => r.BuildId); var releasesByReleaseDefinitionId = (releases ?? new List <Release>()).ToLookup(r => r.ReleaseDefinitionId); var buildSummary = buildDefinitions?.Select(b => Map(b, releaseDefinitionsByBuildId, releasesByReleaseDefinitionId)).ToList(); var repoReleaseDefinitions = Map(releaseDefinitionsForRepo ?? new List <Models.AzureDevops.ReleaseDefinition>(), releasesByReleaseDefinitionId).ToList(); return(new Repository { Id = toMap.id, Name = toMap.name, Url = toMap.weburl, CommitSummary = commitSummary, PullRequestSummary = pullRequestSummary, Branches = branchSummary, BuildDefinitions = buildSummary, ReleaseDefinitions = repoReleaseDefinitions }); }
public IEnumerable<ISiteMapNodeToParentRelation> BuildHierarchy(ISiteMap siteMap, IEnumerable<ISiteMapNodeToParentRelation> nodes) { var sourceNodesByParent = nodes.ToLookup(n => n.ParentKey); var sourceNodes = new List<ISiteMapNodeToParentRelation>(nodes); var nodesAddedThisIteration = 0; do { var nodesAlreadyAdded = new HashSet<string>(); nodesAddedThisIteration = 0; foreach (var node in sourceNodes.OrderBy(x => x.Node.Order).ToArray()) { if (nodesAlreadyAdded.Contains(node.Node.Key)) { continue; } var parentNode = siteMap.FindSiteMapNodeFromKey(node.ParentKey); if (parentNode != null) { this.AddAndTrackNode(siteMap, node, parentNode, sourceNodes, nodesAlreadyAdded); nodesAddedThisIteration += 1; // Add the rest of the tree branch below the current node this.AddDescendantNodes(siteMap, node.Node, sourceNodes, sourceNodesByParent, nodesAlreadyAdded); } } } while (nodesAddedThisIteration > 0 && sourceNodes.Count > 0); return sourceNodes; }
public List<CellName> Ho_Nrel_Get(IEnumerable<小区切换查询> cdd_nrel) { var nrelation = cdd_nrel.ToLookup(e => e.小区名); List<CellName> nrel = new List<CellName>(); int thr = 0; foreach (var n in nrelation) { var nreltop = n.OrderByDescending(e => e.切换次数); foreach (var nn in nreltop) { thr++; if (thr > 5) continue; CellName cn = new CellName(); cn.Cell_name = n.Key; cn.N_cell_name = nn.邻小区名; cn.Handover = nn.切换次数; nrel.Add(cn); } thr = 0; } foreach (var n in nrelation) { CellName cn = new CellName(); cn.Cell_name = n.Key; cn.N_cell_name = n.Key; nrel.Add(cn); } return nrel; }
/// <summary> /// Turns the given object <paramref name="obj"/> into an <see cref="ExpandoObject"/>. /// If <paramref name="obj"/> is: /// <list type="bullet"> /// <item><description> /// <see langword="null"/> then a new empty <see cref="ExpandoObject"/> is returned. /// </description></item> /// <item><description> /// <see cref="NameValueCollection"/>, <see cref="IDictionary"/>, <see cref="ExpandoObject"/> or any /// <see cref="IDictionary{TKey,TValue}"/> then a new expando object with the same source key-value pairs /// is created and returned. Keys are converted to strings if they are not of type <see cref="String"/>. /// </description></item> /// <item><description> /// <see cref="IDataRecord"/> then a new expando objet with the same column name-value pair of the current rader /// row is created and returned. All <see cref="DBNull"/> values are converted to <see langword="null"/> or to the default /// value of the hint type if a <paramref name="typeHint"/> parameter is provided. /// </description></item> /// </list> /// </summary> /// <param name="obj">The source object to convert to an expando object.</param> /// <param name="typeHint">Object or dictionary with values of type <see cref="Type"/>.</param> /// <param name="whitelist">Exhaustive set of properties to include.</param> /// <param name="blacklist">Poperties to exclude.</param> public static ExpandoObject ToExpando( this object obj, object typeHint = null, IEnumerable<string> whitelist = null, IEnumerable<string> blacklist = null) { if (obj == null) { return new ExpandoObject(); } var includeLookup = whitelist == null ? null : whitelist.ToLookup(x => x); var excludeLookup = blacklist == null ? null : blacklist.ToLookup(x => x); if (whitelist != null && blacklist != null && includeLookup.Any() && includeLookup.Any()) { // Slicing can't be done by both including *and* excluding properties throw new InvalidOperationException("Slicing is done using either a white list or a black list"); } var types = typeHint == null ? null : typeHint.ToExpando().Where(p => p.Value is Type).ToDictionary(p => p.Key, p => (Type)p.Value); var result = new ExpandoObject(); var resultDictionary = result as IDictionary<string, object>; ObjectConversionHelper.ProcessProperties( obj, (key, val) => resultDictionary[key] = ChangeType(key, val, types), key => FilterProperty(includeLookup, excludeLookup, key)); return result; }
/// <summary> /// Updates the ParentId, Z, and WindowId properties of all interactors. /// </summary> /// <param name="behaviorMaps">Behavior maps providing the interactors.</param> public static void UpdateInteractorProperties(IEnumerable<BehaviorMap> behaviorMaps) { foreach (var behaviorsByForm in behaviorMaps .ToLookup<BehaviorMap, Form>(map => GetForm(map))) { var form = behaviorsByForm.Key; if (form == null) { continue; } var windowId = form.Handle.ToString(); try { var interactorDictionary = behaviorsByForm .SelectMany(map => map.Interactors) .ToDictionary(x => x.Control); int z = 0; UpdateInteractorProperties(behaviorsByForm.Key, Literals.RootId, ref z, windowId, interactorDictionary); } catch (ArgumentException) // thrown by the ToDictionary operation { throw new InvalidOperationException("A control is referenced by more than one interactor."); } } }
/// <summary> /// Filters properties in this instance by specified property identifiers. /// </summary> /// <param name="propertyIds">The property identifiers.</param> /// <exception cref="System.ArgumentNullException">propertyIds</exception> public void IntersectProperties(IEnumerable<int> propertyIds) { if (propertyIds == null) throw new ArgumentNullException("propertyIds"); ILookup<int, int> requiredIds = propertyIds.ToLookup(t => t); Properties = Properties.Where(p => requiredIds.Contains(p.PropertyId)).ToArray(); }
public LunchOptionViewModel(int pollId, LunchOption lo, IEnumerable<LunchVote> votes) { Id = lo.Id; PollId = pollId; Name = lo.Name; var vLookup = votes.ToLookup(v => v.Score, v => v.User.UserName); Upvotes = vLookup[1].OrderBy(n => n).ToList(); Downvotes = vLookup[-1].OrderBy(n => n).ToList(); }
public void Verify(IEnumerable<SecurityAttributeDescriptor> descriptors) { var descriptorLookup = descriptors.ToLookup(d => d.Signature); foreach (TypeDefinition type in _assembly.MainModule.Types) { AssertDescriptorMatches(descriptorLookup, type.FullName, type); foreach (MethodDefinition method in type.AllMethodsAndConstructors()) AssertDescriptorMatches(descriptorLookup, SignatureFor(method), method); } }
/// <summary> /// Initialises a new instance of the <see cref="Solution" /> class. /// </summary> internal Solution( ISolutionResult solutionResult, IEnumerable <ISolutionCapabilityListResult> solutionCapabilityListResult, IEnumerable <IMarketingContactResult> contactResult, ISolutionSupplierResult solutionSupplierResult, IDocumentResult documentResult, IEnumerable <ISolutionEpicListResult> solutionEpicListResults) { var contactResultList = contactResult.ToList(); var solutionEpicsByCapability = solutionEpicListResults?.ToLookup(e => e.CapabilityId); Id = solutionResult.Id; Name = solutionResult.Name; LastUpdated = GetLatestLastUpdated(solutionResult, contactResultList); Summary = solutionResult.Summary; Description = solutionResult.Description; Features = string.IsNullOrWhiteSpace(solutionResult.Features) ? new List <string>() : JsonConvert.DeserializeObject <IEnumerable <string> >(solutionResult.Features); Integrations = new Integrations { Url = solutionResult.IntegrationsUrl, DocumentName = documentResult?.IntegrationDocumentName }; ImplementationTimescales = new ImplementationTimescales { Description = solutionResult.ImplementationTimescales }; AboutUrl = solutionResult.AboutUrl; RoadMap = new RoadMap { Summary = solutionResult.RoadMap, DocumentName = documentResult?.RoadMapDocumentName }; ClientApplication = string.IsNullOrWhiteSpace(solutionResult.ClientApplication) ? new ClientApplication() : JsonConvert.DeserializeObject <ClientApplication>(solutionResult.ClientApplication); IsFoundation = solutionResult.IsFoundation; Capabilities = solutionCapabilityListResult.Select(c => new ClaimedCapability(c, solutionEpicsByCapability?[c.CapabilityId])); Contacts = contactResultList.Select(c => new Contact(c)); PublishedStatus = solutionResult.PublishedStatus; Hosting = string.IsNullOrWhiteSpace(solutionResult.Hosting) ? new Hosting() : JsonConvert.DeserializeObject <Hosting>(solutionResult.Hosting); Supplier = solutionSupplierResult != null ? new SolutionSupplier(solutionSupplierResult) : new SolutionSupplier(); SolutionDocument = new SolutionDocument(documentResult?.SolutionDocumentName); }
private static IReadOnlyList<DeclarationReference> GetMembersSlow(IEnumerable<Declaration> symbols) { var lookup = symbols .ToLookup(s => s is Namespace); var childSymbols = lookup[false].Cast<Entity>() .Select(e => (DeclarationReference)new EntityReference(e)).ToList(); var childNamespaces = lookup[true].ToList(); if(childNamespaces.Any()) { var childNamespace = new NamespaceReference(childNamespaces.Cast<Namespace>()); childSymbols.Add(childNamespace); } return childSymbols; }
IEnumerable<ResolvedDependency> OverrideDependenciesWithLocalDeclarations(IEnumerable<ResolvedDependency> dependencies, ICollection<WrapDependency> rootDependencies) { var overriddenDependencies = dependencies.ToList(); foreach(var conflictingDependency in dependencies.ToLookup(x=>x.Package.Name).Where(x=>x.Count() > 1)) { var dependencyName = conflictingDependency.Key; var rootDependency = rootDependencies.FirstOrDefault(x => x.Name == dependencyName); if (rootDependency == null) continue; var rescuedDependency = conflictingDependency.OrderByDescending(x => x.Package.Version).FirstOrDefault(x => rootDependency.IsFulfilledBy(x.Package.Version)); if (rescuedDependency == null) continue; foreach (var toRemove in conflictingDependency.Where(x=>x != rescuedDependency)) overriddenDependencies.Remove(toRemove); } return overriddenDependencies; }
public static AutoCompleteController ForTimer(IEnumerable<Toggl.TogglAutocompleteView> items) { var splitList = items.ToLookup(i => string.IsNullOrEmpty(i.Description)); var entries = splitList[false]; var projects = splitList[true]; int entriesCount; int projectsCount; var list = new List<IAutoCompleteListItem> { new SimpleNoncompletingCategory("Time Entries", entries.Select(i => new TimerItem(i, false)).ToList<IAutoCompleteListItem>().GetCount(out entriesCount) ), new SimpleNoncompletingCategory("Projects", projects.Select(i => new TimerItem(i, true)).ToList<IAutoCompleteListItem>().GetCount(out projectsCount) ) }; return new AutoCompleteController(list, string.Format("Timer(entries: {0}, projects: {1})", entriesCount, projectsCount)); }
public DeleteTagResponse DeleteTags(DeleteTagIdsRequest request) { Logger.Current.Verbose("Request to delete the Tag."); bool isAssociatedWithWorkflow = tagRepository.isAssociatedWithWorkflows(request.TagID); bool isAssociatedWithLeadScoreRules = tagRepository.isAssociatedWithLeadScoreRules(request.TagID); if (isAssociatedWithLeadScoreRules && isAssociatedWithWorkflow) { throw new UnsupportedOperationException("[|The selected Tag(s) is associated with Workflows and Lead Score Rules|]. [|Delete operation cancelled|]."); } else if (isAssociatedWithLeadScoreRules) { throw new UnsupportedOperationException("[|The selected Tag(s) is associated with lead score|]. [|Delete operation cancelled|]."); } else if (isAssociatedWithWorkflow) { throw new UnsupportedOperationException("[|The selected Tag(s) is associated with Workflow|]. [|Delete operation cancelled|]."); } IEnumerable <int> contactIds = tagRepository.DeleteTags(request.TagID, request.AccountId); int count = 0; foreach (var tagid in request.TagID) { count = count + indexingService.RemoveTag(tagid, request.AccountId); Logger.Current.Verbose("Removed the tag " + tagid + " from elastic search."); } if (contactIds != null && contactIds.Any()) { contactService.ContactIndexing(new ContactIndexingRequest() { ContactIds = contactIds.ToList(), Ids = contactIds.ToLookup(o => o, o => { return(true); }) }); } Logger.Current.Verbose("Total deleted tags:" + request.TagID.Count() + ". Total deleted tags from elastic search. Response count from elastic search: " + count); return(new DeleteTagResponse()); }
private IReadOnlyCollection <Operation> BuildCodeCountOperationList( Guid valueSetGuid, IEnumerable <ValueSetCodeDto> allCodeDtos) { var originalCounts = this.uowManager.GetCodeCountDtos(valueSetGuid); var allCodesByCodeSystem = allCodeDtos.ToLookup(c => c.CodeSystemGuid); var recounts = (from g in allCodesByCodeSystem let valueSetDto = g.First() select new ValueSetCodeCountDto( valueSetDto.ValueSetGUID, valueSetDto.CodeSystemGuid, valueSetDto.CodeSystemNM, g.Count())).ToList(); var operations = recounts.Select( recount => originalCounts.Where(oc => oc.CodeSystemGUID == recount.CodeSystemGUID) .FirstMaybe() .Select(dto => GetCodeSystemRecountOperation(dto, recount)) .Else(() => new Operation { Value = recount })) .Where(operation => operation.OperationType != OperationType.None) .ToList(); // finally ensure that any existing counts that were not in the new counts are removed // e.g. all codes from a particular code system were removed var removers = originalCounts.Where(oc => !allCodesByCodeSystem.Contains(oc.CodeSystemGUID)); operations.AddRange( removers.Select(r => new Operation { Value = r, OperationType = OperationType.Delete })); return(operations.ToList()); }
public static IEnumerable <TResult> LeftJoin <TLeft, TRight, TKey, TResult>([NotNull] this IEnumerable <TLeft> left, [NotNull] IEnumerable <TRight> right, [NotNull] Func <TLeft, TKey> leftKeySelector, [NotNull] Func <TRight, TKey> rightKeySelector, [NotNull] Func <TLeft, TRight, TResult> projection) { if (left == null) { throw new ArgumentNullException(nameof(left)); } if (right == null) { throw new ArgumentNullException(nameof(right)); } if (leftKeySelector == null) { throw new ArgumentNullException(nameof(leftKeySelector)); } if (rightKeySelector == null) { throw new ArgumentNullException(nameof(rightKeySelector)); } if (projection == null) { throw new ArgumentNullException(nameof(projection)); } var rightLookup = right.ToLookup(rightKeySelector); foreach (var leftItem in left) { var rightItem = rightLookup[leftKeySelector(leftItem)].SingleOrDefault(); yield return(projection(leftItem, rightItem)); } }
internal static void DeleteFiles(this IFileSystem fileSystem, IEnumerable <IPackageFile> files, string rootDir) { // First get all directories that contain files var directoryLookup = files.ToLookup(p => Path.GetDirectoryName(p.Path)); // Get all directories that this package may have added var directories = from grouping in directoryLookup from directory in GetDirectories(grouping.Key) orderby directory.Length descending select directory; // Remove files from every directory foreach (var directory in directories) { var directoryFiles = directoryLookup.Contains(directory) ? directoryLookup[directory] : Enumerable.Empty <IPackageFile>(); string dirPath = Path.Combine(rootDir, directory); if (!fileSystem.DirectoryExists(dirPath)) { continue; } foreach (var file in directoryFiles) { string path = Path.Combine(rootDir, file.Path); fileSystem.DeleteFileSafe(path, file.GetStream); } // If the directory is empty then delete it if (!fileSystem.GetFilesSafe(dirPath).Any() && !fileSystem.GetDirectoriesSafe(dirPath).Any()) { fileSystem.DeleteDirectorySafe(dirPath, recursive: false); } } }
public IEnumerable <T> Sort() { var sourceCount = _source.Count(); var result = new List <T>(sourceCount); var lookup = _source.ToLookup(x => x.ParentCategoryId); result.AddRange(SortInternal(_parentId, lookup)); if (!_ignoreDetachedCategories && result.Count != sourceCount) { // Find categories without parent in provided category source and insert them into result. var resultLookup = result.ToDictionarySafe(x => x.Id); foreach (var cat in _source) { if (!resultLookup.ContainsKey(cat.Id)) { result.Add(cat); } } } return(result); }
Pivot <TSource, TFirstKey, TSecondKey, TValue>( this IEnumerable <TSource> source, Func <TSource, TFirstKey> firstKeySelector, Func <TSource, TSecondKey> secondKeySelector, Func <IEnumerable <TSource>, TValue> aggregate) { var retVal = new Dictionary <TFirstKey, Dictionary <TSecondKey, TValue> >(); var l = source.ToLookup(firstKeySelector); foreach (var item in l) { var dict = new Dictionary <TSecondKey, TValue>(); retVal.Add(item.Key, dict); var subdict = item.ToLookup(secondKeySelector); foreach (var subitem in subdict) { dict.Add(subitem.Key, aggregate(subitem)); } } return(retVal); }
private static IEnumerable <TResult> JoinImpl <TOuter, TInner, TKey, TResult>( IEnumerable <TOuter> outer, IEnumerable <TInner> inner, Func <TOuter, TKey> outerKeySelector, Func <TInner, TKey> innerKeySelector, Func <TOuter, TInner, TResult> resultSelector, IEqualityComparer <TKey> comparer) { #if EMULATE_LINQ_TO_OBJECTS_DISCARDING_NULL_KEYS var lookup = inner.ToLookupNoNullKeys(innerKeySelector, comparer); #else var lookup = inner.ToLookup(innerKeySelector, comparer); #endif // If only we had "yield foreach"... we can't just return outer.SelectMany(...), as we'd // get immediate execution for the lookup. var results = outer.SelectMany(outerElement => lookup[outerKeySelector(outerElement)], resultSelector); foreach (var result in results) { yield return(result); } }
public CustomControllerSelector(string suffix) { Suffix = suffix; HttpConfiguration config = GlobalConfiguration.Configuration; IHttpControllerTypeResolver typeFinder = config.Services.GetHttpControllerTypeResolver(); IAssembliesResolver assemblyFinder = config.Services.GetAssembliesResolver(); IEnumerable <HttpControllerDescriptor> descriptors = typeFinder.GetControllerTypes(assemblyFinder) .Select(type => new HttpControllerDescriptor { Configuration = GlobalConfiguration.Configuration, ControllerName = type.Name.Substring(0, type.Name.Length - Suffix.Length), ControllerType = type }); mappings = descriptors.ToLookup(descriptor => descriptor.ControllerName, StringComparer.OrdinalIgnoreCase); dictionary = descriptors.ToDictionary(d => d.ControllerName, d => d); }
public static IEnumerable <TResult> FullOuterJoin <TOuter, TInner, TKey, TResult>( this IEnumerable <TOuter> outer, IEnumerable <TInner> inner, Func <TOuter, TKey> outerKeySelector, Func <TInner, TKey> innerKeySelector, Func <TOuter, TInner, TResult> resultSelector) where TInner : class where TOuter : class { var innerLookup = inner.ToLookup(innerKeySelector); var outerLookup = outer.ToLookup(outerKeySelector); var innerJoinItems = inner .Where(innerItem => !outerLookup.Contains(innerKeySelector(innerItem))) .Select(innerItem => resultSelector(null, innerItem)); return(outer .SelectMany(outerItem => { var innerItems = innerLookup[outerKeySelector(outerItem)]; return innerItems.Any() ? innerItems : new TInner[] { null }; }, resultSelector) .Concat(innerJoinItems)); }
public static IEnumerable <TResult> FullOuterJoin <TA, TB, TKey, TResult>( this IEnumerable <TA> a, IEnumerable <TB> b, Func <TA, TKey> selectKeyA, Func <TB, TKey> selectKeyB, Func <TKey, TA, TB, TResult> projection, TA defaultA = default(TA), TB defaultB = default(TB), IEqualityComparer <TKey> cmp = null) { cmp = cmp ?? EqualityComparer <TKey> .Default; var aLookup = a.ToLookup(selectKeyA, cmp); var bLookup = b.ToLookup(selectKeyB, cmp); var keys = aLookup.Select(p => p.Key).Concat(bLookup.Select(p => p.Key)).Distinct(); var join = from key in keys from xa in aLookup[key].DefaultIfEmpty(defaultA) from xb in bLookup[key].DefaultIfEmpty(defaultB) select projection(key, xa, xb); return(join); }
public Dictionary <string, Dictionary <string, IEnumerable <string> > > Convert(IEnumerable <PermissionMeta> source, Dictionary <string, Dictionary <string, IEnumerable <string> > > destination, ResolutionContext context) { var permissionMetaLookups = source.ToLookup(a => a.Module); var result = new Dictionary <string, Dictionary <string, IEnumerable <string> > >(); foreach (var permissionMetaLookup in permissionMetaLookups) { var auths = new Dictionary <string, IEnumerable <string> >(); var authsLookups = permissionMetaLookup.ToLookup(p => p.Auth); foreach (var authsLookup in authsLookups) { var authRouteNameList = authsLookup.Select(l => $"{l.RouteName}+{l.MethodName}"); auths.Add(authsLookup.Key, authRouteNameList); } result.Add(permissionMetaLookup.Key, auths); } return(result); }
public static IEnumerable <TR> FullOuterJoin <TA, TB, TK, TR>( this IEnumerable <TA> a, IEnumerable <TB> b, Func <TA, TK> selectKeyA, Func <TB, TK> selectKeyB, Func <TA, TB, TK, TR> projection, TA defaultA = default(TA), TB defaultB = default(TB), IEqualityComparer <TK> cmp = null) { cmp = cmp ?? EqualityComparer <TK> .Default; ILookup <TK, TA> alookup = a.ToLookup(selectKeyA, cmp); ILookup <TK, TB> blookup = b.ToLookup(selectKeyB, cmp); var keys = new HashSet <TK>(alookup.Select(p => p.Key), cmp); keys.UnionWith(blookup.Select(p => p.Key)); return(from key in keys from xa in alookup[key].DefaultIfEmpty(defaultA) from xb in blookup[key].DefaultIfEmpty(defaultB) select projection(xa, xb, key)); }
internal static IList <TR> FullOuterGroupJoin <TA, TB, TK, TR>( this IEnumerable <TA> a, IEnumerable <TB> b, Func <TA, TK> selectKeyA, Func <TB, TK> selectKeyB, Func <IEnumerable <TA>, IEnumerable <TB>, TK, TR> projection, IEqualityComparer <TK> cmp = null) { cmp = cmp ?? EqualityComparer <TK> .Default; var alookup = a.ToLookup(selectKeyA, cmp); var blookup = b.ToLookup(selectKeyB, cmp); var keys = new HashSet <TK>(alookup.Select(p => p.Key), cmp); keys.UnionWith(blookup.Select(p => p.Key)); var join = from key in keys let xa = alookup[key] let xb = blookup[key] select projection(xa, xb, key); return(join.ToList()); }
// Group the employees in the following salary ranges: 200-399, 400-599, 600-799, 800-999 public static void SalaryGroups() { Console.WriteLine("************************************\nGroup the employees in the following salary ranges: 200-399, 400-599, 600-799, 800-999"); var query1 = employees.MyToDictionary <string, Employee>(SalaryGroups_Groupper); var query2 = employees.ToLookup(SalaryGroups_Groupper); var query3 = employees.GroupBy(SalaryGroups_Groupper); Console.WriteLine("Solution 1"); foreach (var group in query1) { Console.WriteLine($"\ngroup: {group.Key}"); foreach (var item in group.Value) { Console.WriteLine(item); } } Console.WriteLine("Solution 2"); foreach (var group in query2) { Console.WriteLine($"\ngroup: {group.Key}"); foreach (var item in group) { Console.WriteLine(item); } } Console.WriteLine("Solution 3"); foreach (var group in query3) { Console.WriteLine($"\ngroup: {group.Key}"); foreach (var item in group) { Console.WriteLine(item); } } }
/// <summary> /// Provided an array of entities will set the condition to retrieve the same entities based in the primary key /// Handy to retrieve the same rows (with same primary keys) of the same table between different SAP systems /// </summary> public TableReader <T> WhereByKeys(IEnumerable <T> entities) { //Remove duplicated entries entities = entities .ToLookup(e => TableReaderExtensions.SerializeKeyColumns(e)) .Select(e => e.First()); var keyCols = TableReaderExtensions.GetKeyColumns <T>(); if (keyCols.IsEmpty()) { throw new ArgumentException($"At least one property of {_rowType.Name} must have the 'Key' attribute."); } _condition = new WhereBuilder(); if (keyCols.IsEmpty()) { throw new ArgumentException(); } foreach (var row in entities) { var expression = string.Empty; foreach (var keyCol in keyCols) { var propVal = _accesor[row, keyCol]; expression += $"{keyCol} = " + (propVal.GetType().IsNumber() ? propVal : $"'{propVal}'") + " AND "; } expression = expression.ReplaceLastOccurrence(" AND ", string.Empty); (_condition.Conditions as List <string>).Add(expression); } return(this); }
public static IEnumerable <TResult> FullOuterJoin <TA, TB, TKey, TResult>( [NotNull] this IEnumerable <TA> a, [NotNull] IEnumerable <TB> b, [NotNull] Func <TA, TKey> selectKeyA, [NotNull] Func <TB, TKey> selectKeyB, [NotNull] Func <TA, TB, TKey, TResult> projection, TA defaultA = default, TB defaultB = default, IEqualityComparer <TKey> cmp = null) { cmp = cmp ?? EqualityComparer <TKey> .Default; ILookup <TKey, TA> alookup = a.ToLookup(selectKeyA, cmp); ILookup <TKey, TB> blookup = b.ToLookup(selectKeyB, cmp); HashSet <TKey> keys = new HashSet <TKey>(alookup.Select(p => p.Key), cmp); keys.UnionWith(blookup.Select(p => p.Key)); return (from key in keys from xa in alookup[key].DefaultIfEmpty(defaultA) from xb in blookup[key].DefaultIfEmpty(defaultB) select projection(xa, xb, key)); }
private IEnumerable <ReplicateGroup> GetReplicateGroups(IEnumerable <int> replicateIndexes) { var chromatograms = _document.Settings.MeasuredResults.Chromatograms; if (ReplicateGroupOp.GroupByAnnotation == null) { return (replicateIndexes.Select(replicateIndex => new ReplicateGroup(chromatograms[replicateIndex].Name, ReplicateIndexSet.Singleton(replicateIndex)))); } var lookup = replicateIndexes.ToLookup(replicateIndex => chromatograms[replicateIndex].Annotations.GetAnnotation(ReplicateGroupOp.GroupByAnnotation)); var keys = lookup.Select(grouping => grouping.Key).ToList(); if (keys.Count > 2) { // If there are more than 2 groups then exclude replicates with blank annotation values. keys.Remove(null); } keys.Sort(); // ReSharper disable AssignNullToNotNullAttribute return(keys.Select(key => new ReplicateGroup((key ?? string.Empty).ToString(), ReplicateIndexSet.OfValues(lookup[key])))); // ReSharper restore AssignNullToNotNullAttribute }
/// <summary> /// Reads all the Smart Detectors manifests from the repository. /// For each Smart Detector we return the latest version's manifest. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A <see cref="Task{TResult}"/> returning the Smart Detectors manifests</returns> public async Task <IList <SmartDetectorManifest> > ReadAllSmartDetectorsManifestsAsync(CancellationToken cancellationToken) { // We don't want to open the Smart Detector packages to get the manifest so we read it from the blob's metadata this.tracer.TraceInformation("Getting all Smart Detectors manifests from the blob metadata"); try { var allSmartDetectorsManifests = new List <SmartDetectorManifest>(); IEnumerable <CloudBlob> blobs = (await this.containerClient.ListBlobsAsync(string.Empty, true, BlobListingDetails.Metadata, cancellationToken)).Cast <CloudBlob>().Where(blob => blob.Metadata.ContainsKey("id")); ILookup <string, CloudBlob> smartDeterctorIdToAllVersionsLookup = blobs.ToLookup(blob => blob.Metadata["id"], blob => blob); foreach (IGrouping <string, CloudBlob> smartDeterctorVersionsGroup in smartDeterctorIdToAllVersionsLookup) { string smartDeterctorId = smartDeterctorVersionsGroup.Key; if (string.IsNullOrWhiteSpace(smartDeterctorId)) { // blob is not a Smart Detector continue; } // Get the latest version blob of the Smart Detector CloudBlob latestVersionSmartDetectorBlob = GetLatestVersionSmartDetectorBlob(smartDeterctorIdToAllVersionsLookup[smartDeterctorId]); if (latestVersionSmartDetectorBlob != null) { // Generate the manifest from the blob's metadata allSmartDetectorsManifests.Add(GenerateSmartDetectorManifest(latestVersionSmartDetectorBlob)); } } return(allSmartDetectorsManifests); } catch (StorageException e) { throw new SmartDetectorRepositoryException("Failed to get all Smart Detector manifests from storage", e); } }
public static IEnumerable <TResult> GroupJoin <TOuter, TInner, TKey, TResult> (this IEnumerable <TOuter> outer, IEnumerable <TInner> inner, Func <TOuter, TKey> outerKeySelector, Func <TInner, TKey> innerKeySelector, Func <TOuter, IEnumerable <TInner>, TResult> resultSelector) { ILookup <TKey, TInner> innerLookup = inner.ToLookup(innerKeySelector); foreach (TOuter outerElement in outer) { TKey key = outerKeySelector(outerElement); IEnumerable <TInner> innerMatches; if (innerLookup.Contains(key)) { innerMatches = innerLookup[key]; } else { innerMatches = Empty <TInner>(); } yield return(resultSelector(outerElement, innerMatches)); } }
private void AfterUpdate(IEnumerable <CollectionModel> collectionDocumentsCount) { // update documents count var nameToCount = collectionDocumentsCount.ToLookup(i => i.Name, i => i.Count); foreach (var collectionModel in Collections) { collectionModel.Count = nameToCount[collectionModel.Name].Sum(); } initialSelectedCollectionName = initialSelectedCollectionName ?? ""; if ((SelectedCollection.Value == null || SelectedCollection.Value.Name != initialSelectedCollectionName || Collections.Contains(SelectedCollection.Value) == false)) { SelectedCollection.Value = Collections.FirstOrDefault(x => x.Name == initialSelectedCollectionName); } if (SelectedCollection.Value == null) { SelectedCollection.Value = Collections.FirstOrDefault(); } SortedCollectionsList.View.Refresh(); }
private static IEnumerable <ContributorSummary> Map(IEnumerable <Models.AzureDevops.GitCommitRef> commits) { //For Git commits, author vs committer here is a good explanation: //https://stackoverflow.com/questions/18750808/difference-between-author-and-committer-in-git // Email addresses and names can be inconsistent. (ex: [email protected] and [email protected] can both be there but are the same person) var nameByEmail = commits.ToLookup(c => c?.author?.email ?? "unknown") .ToDictionary(g => g?.Key ?? "unknown", g => g?.FirstOrDefault()?.author?.name ?? "unknown"); return(commits? .GroupBy(c => nameByEmail[c.author.email]) .Select(g => new ContributorSummary { AuthorName = g.Key, CommitCount = g.Count(), LastActivity = g.Max(c => c?.author?.date?.Date), Additions = g.Sum(c => c.changeCounts?.Add), Edits = g.Sum(c => c.changeCounts?.Edit), Deletions = g.Sum(c => c.changeCounts?.Delete), }) .OrderByDescending(c => c.LastActivity)); }
public static IEnumerable <TResult> FullOuterJoin <TA, TB, TKey, TResult>( this IEnumerable <TA> a, IEnumerable <TB> b, Func <TA, TKey> selectKeyA, Func <TB, TKey> selectKeyB, Func <TA, TB, TKey, TResult> projection) { var defaultA = default(TA); var defaultB = default(TB); var cmp = EqualityComparer <TKey> .Default; var alookup = a.ToLookup(selectKeyA, cmp); var blookup = b.ToLookup(selectKeyB, cmp); var keys = new HashSet <TKey>(alookup.Select(p => p.Key), cmp); keys.UnionWith(blookup.Select(p => p.Key)); var join = from key in keys from xa in alookup[key].DefaultIfEmpty(defaultA) from xb in blookup[key].DefaultIfEmpty(defaultB) select projection(xa, xb, key); return(join); }
/// <summary> /// 将数据源转化为适用于 ListView 分组的数据模型 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="groupKey">分组依据</param> /// <returns></returns> public static IEnumerable <Grouped <T> > ToGroup <T>(this IEnumerable <T> source, Func <T, object> groupKey, Func <T, object> sortKey = null ) { var a = source.ToLookup(groupKey) .Select(l => { var title = l.Key?.ToString(); var shortTitle = "#"; if (!string.IsNullOrEmpty(title)) { shortTitle = title.Substring(0, 1); } return(new Grouped <T>(l, sortKey) { Title = title, ShortTitle = shortTitle }); }); return(a); }
public void CopyItems(IEnumerable <ITimelineItem> items) { using (new TimelineUndo.DisableUndoGuard(true)) { var itemsByParent = items.ToLookup(i => i.parentTrack); foreach (var itemsGroup in itemsByParent) { var parent = itemsGroup.Key; var itemsList = new List <ITimelineItem>(); foreach (var item in itemsGroup) { if (item is ClipItem) { itemsList.Add(CopyItem((ClipItem)item)); } else if (item is MarkerItem) { itemsList.Add(CopyItem((MarkerItem)item)); } } m_ItemsData.Add(new ItemsPerTrack(parent, itemsList)); } } }
private void SetReferenceLocations(IEnumerable <InlineRenameLocation> locations) { AssertIsForeground(); var locationsByDocument = locations.ToLookup(l => l.Document.Id); _isApplyingEdit = true; foreach (var textBuffer in _openTextBuffers.Keys) { var documents = textBuffer.AsTextContainer().GetRelatedDocuments(); if (!documents.Any(d => locationsByDocument.Contains(d.Id))) { _openTextBuffers[textBuffer].SetReferenceSpans(SpecializedCollections.EmptyEnumerable <TextSpan>()); } else { var spans = documents.SelectMany(d => locationsByDocument[d.Id]).Select(l => l.TextSpan).Distinct(); _openTextBuffers[textBuffer].SetReferenceSpans(spans); } } _isApplyingEdit = false; }
private void ValidateRequiredArguments( ISyntaxNode parent, IEnumerable <ArgumentNode> providedArguments, IFieldCollection <IInputField> arguments) { ILookup <string, ArgumentNode> providedArgumentLookup = providedArguments.ToLookup(t => t.Name.Value); foreach (InputField requiredArgument in arguments .Where(t => IsRequiredArgument(t))) { ArgumentNode providedArgument = providedArgumentLookup[requiredArgument.Name] .FirstOrDefault(); if (providedArgument == null || providedArgument.Value is NullValueNode) { Errors.Add(new ValidationError( $"The argument `{requiredArgument.Name}` is required " + "and does not allow null values.", parent)); } } }
private static Plot GetBoxplot(IEnumerable <PlotData> data, string referenceFactor) { var plot = new Plot(200, 100); var orderedGroupingData = data .ToLookup(bd => bd.Group) .OrderBy(x => x.Key == referenceFactor ? -1 : 1) .ToList(); var populationMultiSeries = new PopulationMultiSeries(orderedGroupingData.Select(grouping => { var plottingData = grouping.Where(g => g.Value.HasValue).Select(g => g.Value.Value).ToArray(); return(new PopulationSeries(new Population[] { new Population(plottingData) }, grouping.Key)); }).ToArray()); var populationChart = plot.PlotPopulations(populationMultiSeries); populationChart.displayDistributionCurve = false; populationChart.displayItems = PlottablePopulations.DisplayItems.BoxOnly; populationChart.boxStyle = PlottablePopulations.BoxStyle.BoxMedianQuartileOutlier; plot.Frame(false); plot.Ticks(false); return(plot); }
public DependentHandler( IEnumerable< string > args, string key ) { this.args = args.ToLookup( s => s.ToUpper(), s => key.ToUpper() ); this.val = key; }
private static ILookup<string, FileSystemPath> ToLookup(IEnumerable<IVsPackageMetadata> packages) { return packages.ToLookup(_ => _.Id, _ => new FileSystemPath(_.InstallPath), StringComparer.OrdinalIgnoreCase); }
private void SetReferenceLocations(IEnumerable<InlineRenameLocation> locations) { AssertIsForeground(); var locationsByDocument = locations.ToLookup(l => l.Document.Id); _isApplyingEdit = true; foreach (var textBuffer in _openTextBuffers.Keys) { var documents = textBuffer.AsTextContainer().GetRelatedDocuments(); if (!documents.Any(d => locationsByDocument.Contains(d.Id))) { _openTextBuffers[textBuffer].SetReferenceSpans(SpecializedCollections.EmptyEnumerable<TextSpan>()); } else { var spans = documents.SelectMany(d => locationsByDocument[d.Id]).Select(l => l.TextSpan).Distinct(); _openTextBuffers[textBuffer].SetReferenceSpans(spans); } } _isApplyingEdit = false; }
// ReSharper disable once ParameterTypeCanBeEnumerable.Local void CheckDataListItemsForDuplicates(IEnumerable<IDataListItemModel> itemsToCheck) { List<IGrouping<string, IDataListItemModel>> duplicates = itemsToCheck.ToLookup(x => x.Name).ToList(); foreach(var duplicate in duplicates) { if(duplicate.Count() > 1 && !String.IsNullOrEmpty(duplicate.Key)) { duplicate.ForEach(model => model.SetError(StringResources.ErrorMessageDuplicateValue)); } else { duplicate.ForEach(model => { if(model.ErrorMessage != null && model.ErrorMessage.Contains(StringResources.ErrorMessageDuplicateValue)) { model.RemoveError(); } }); } } }
public void AssertQuantityChecking(IEnumerable<IOStockDataGridItem> items) { var lookup = items.ToLookup(x => x.Inventory); foreach (var item in lookup) { var orderedItem = item.OrderBy(x => x.Date); var lastItem = orderedItem.Last(); Assert.AreEqual(lastItem.RemainingQuantity, item.Key.Quantity); int? reQty = null; int iosQty, exp; foreach (var i in orderedItem) { iosQty = i.Quantity; if (i.StockType == IOStockType.OUTGOING) iosQty = -iosQty; if (reQty == null) reQty = 0; exp = (int)reQty + iosQty; Assert.AreEqual(i.RemainingQuantity, exp); reQty = exp; } } }
public StyleMatcher(IEnumerable<IStyle> styles) { Styles = styles.ToLookup(s => s.ControlType); }
/// <summary> /// Group all DBOs and return the readouts /// </summary> /// <param name="myDBObjectStreams"></param> /// <param name="mySelections"></param> /// <param name="myReferencedDBType"></param> /// <returns></returns> private IEnumerable<Vertex> ExamineDBO_Groupings(IEnumerable<Exceptional<DBObjectStream>> myDBObjectStreams, List<SelectionElement> mySelections, GraphDBType myReferencedDBType) { #region Create groupings using the ILookup var _GroupedVertices = myDBObjectStreams.ToLookup((dbo) => { CheckLoadedDBObjectStream(dbo, myReferencedDBType); #region Create GroupingKey based on the group values and attributes var groupingVals = new Dictionary<GroupingValuesKey, IObject>(); foreach (var selection in mySelections) { if (!dbo.Value.HasAttribute(selection.Element, _DBContext)) { continue; } var attrValue = dbo.Value.GetAttribute(selection.Element, myReferencedDBType, _DBContext); if (attrValue.Failed()) { throw new GraphDBException(attrValue.IErrors); } groupingVals.Add(new GroupingValuesKey(selection.Element, selection.Alias), attrValue.Value); } GroupingKey groupingKey = new GroupingKey(groupingVals); #endregion return groupingKey; }, (dbo) => { CheckLoadedDBObjectStream(dbo, myReferencedDBType); return dbo.Value; }); #endregion foreach (var group in _GroupedVertices) { #region No valid grouping keys found if (group.Key.Values.IsNullOrEmpty()) { continue; } #endregion var groupedAttributes = new Dictionary<String, Object>(); foreach (var groupingKeyVal in group.Key.Values) { groupedAttributes.Add(groupingKeyVal.Key.AttributeAlias, groupingKeyVal.Value.GetReadoutValue()); } var _VertexGroup = new VertexGroup(groupedAttributes, group.Select(_DBObjectStream => new Vertex(GetAllSelectedAttributesFromVertex(_DBObjectStream, myReferencedDBType, -1, null, null, false, true)))); #region Check having if (_HavingExpression != null) { var res = _HavingExpression.IsSatisfyHaving(_VertexGroup, _DBContext); if (res.Failed()) throw new GraphDBException(res.IErrors); else if (res.Value) yield return _VertexGroup; } else { yield return _VertexGroup; } #endregion } }
/// <summary> /// Selects most common ClassLabel, breaking ties randomly /// </summary> private static TreeNode PluralityValue(IEnumerable<Example> examples) { var classLabel = examples.ToLookup(x => x.ClassLabel) .OrderByDescending(x => x.Count()) .First() .Key; return new TreeNode { ClassLabel = classLabel, }; }
/// <summary> /// ObservableInventory 객체들을 왼, 오른쪽 데이터 그리드에 각각 배치한다. /// </summary> /// <param name="items"></param> /// <param name="doClear">기존의 데이터를 지우고 데이터를 추가할 경우 true, 아니면 false</param> protected void PushDataGridItems(IEnumerable<ObservableInventory> items, bool doClear = false) { if (items == null) return; if (doClear) { DataGridViewModel1.Items.Clear(); DataGridViewModel2.Items.Clear(); DataGridViewModel1.SelectedItem = null; DataGridViewModel2.SelectedItem = null; } var loopup = items.ToLookup(x => x.Product); var orderedItems = loopup.OrderBy(x => x.Key.Name); var dataGridItems1 = DataGridViewModel1.Items; var dataGridItems2 = DataGridViewModel2.Items; foreach (var key in orderedItems) { var orderedInvens = key.OrderBy(x => x.Specification); if (dataGridItems1.Count() == 0 || dataGridItems1.Count() <= dataGridItems2.Count()) orderedInvens.ToList().ForEach(x => dataGridItems1.Add(x)); else orderedInvens.ToList().ForEach(x => dataGridItems2.Add(x)); } }
private static ILookup<string, DiagnosticData> CreateDiagnosticIdLookup(IEnumerable<DiagnosticData> diagnostics) { return diagnostics.ToLookup(d => d.Id); }
private IList GetCookies(HttpCookieCollection cookieCollection, IEnumerable<string> ignoredFormNames) { var ignored = ignoredFormNames.ToLookup(s => s); return Enumerable.Range(0, cookieCollection.Count) .Select(i => cookieCollection[i]) .Where(c => !ignored.Contains(c.Name)) .Select(c => new Cookie(c.Name, c.Value)) .ToList(); }
private IEnumerable<BondSpreadMergedResult> MergeLiveAndCloseResults(IEnumerable<BondSpreadResult> liveBondSpreads, IEnumerable<BondSpreadResult> closeBondSpreads) { if (liveBondSpreads == null || closeBondSpreads == null) return null; var liveBondSpreadsLookup = liveBondSpreads.ToLookup(x => x.Ticker); return closeBondSpreads.Select(b => new BondSpreadMergedResult { Ticker = b.Ticker, Cusip = b.Cusip, ISIN = b.ISIN, Coupon = b.Coupon, IssueDate = b.IssueDate, EffectiveDate = b.EffectiveDate, Maturity = b.Maturity, Term = b.Term, Series = b.Series, InstrumentType = b.InstrumentType, CtdFlag = b.CtdFlag, CtFlag = b.CtFlag, ClosePrice = b.Price, CloseYield = b.Yield, CloseLOAS = b.LOAS, CloseOISOAS = b.OISOAS, CloseForwardPriceFront = b.ForwardPriceFront, CloseFwdLOASFront = b.FwdLOASFront, CloseFwdOISOASFront = b.FwdOISOASFront, CloseForwardPriceBack = b.ForwardPriceBack, CloseFwdLOASBack = b.FwdLOASBack, CloseFwdOISOASBack = b.FwdOISOASBack, LivePrice = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().Price : double.NaN, LiveYield = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().Yield : double.NaN, LiveLOAS = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().LOAS : double.NaN, LiveOISOAS = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().OISOAS : double.NaN, LiveForwardPriceFront = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().ForwardPriceFront : double.NaN, LiveFwdLOASFront = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().FwdLOASFront : double.NaN, LiveFwdOISOASFront = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().FwdOISOASFront : double.NaN, LiveForwardPriceBack = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().ForwardPriceBack : double.NaN, LiveFwdLOASBack = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().FwdLOASBack : double.NaN, LiveFwdOISOASBack = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().FwdOISOASBack : double.NaN, FrontUsedRepo = b.FrontUsedRepo, BackUsedRepo = b.BackUsedRepo, LiveBondPriceUsed = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().BondPriceUsed : double.NaN, CloseBondPriceUsed = b.BondPriceUsed, CtdBondCusipUsed = b.CtdBondCusipUsed, CalcTime = DateTime.Now, LivePriceTimeLocal = liveBondSpreadsLookup[b.Ticker].FirstOrDefault() != null ? liveBondSpreadsLookup[b.Ticker].First().LivePriceTimeUtc.ToLocalTime() : DateTime.MinValue, }); }
private IList<IPackageAssemblyReference> FilterAssemblyReferences( IEnumerable<IPackageAssemblyReference> unfilteredAssemblyReferences, IList<PackageReferenceSet> packageReferenceSets) { if (packageReferenceSets.IsEmpty()) { return unfilteredAssemblyReferences.ToList(); } var results = new List<IPackageAssemblyReference>(); // we group assembly references by TargetFramework var assembliesGroupedByFx = unfilteredAssemblyReferences.ToLookup(d => d.TargetFramework); foreach (var group in assembliesGroupedByFx) { FrameworkName fileTargetFramework = group.Key; IEnumerable<PackageReferenceSet> bestMatches; if (VersionUtility.TryGetCompatibleItems(fileTargetFramework, PackageReferenceSets, out bestMatches)) { // now examine each assembly file, check if it appear in the References list for the correponding target framework foreach (var assemblyFile in group) { if (bestMatches.Any(m => m.References.Contains(assemblyFile.Name))) { results.Add(assemblyFile); } } } } return results; }
/// <summary> /// Go through each DBO and aggregate them /// </summary> /// <param name="myAggregates"></param> /// <param name="mySelections"></param> /// <param name="myDBOs"></param> /// <param name="myReferencedDBType"></param> /// <returns></returns> private IEnumerable<Vertex> ExamineDBO_Aggregates(IEnumerable<Exceptional<DBObjectStream>> myDBOs, List<SelectionElementAggregate> myAggregates, List<SelectionElement> mySelections, GraphDBType myReferencedDBType, Boolean myUsingGraph) { #region Aggregate if (mySelections.CountIsGreater(0)) { #region Grouping - each selection is grouped (checked prior) var aggregatedGroupings = new Dictionary<GroupingKey, SelectionElementAggregate>(); #region Create groupings using the ILookup var groupedDBOs = myDBOs.ToLookup((dbo) => { CheckLoadedDBObjectStream(dbo, myReferencedDBType); #region Create GroupingKey based on the group values and attributes Dictionary<GroupingValuesKey, IObject> groupingVals = new Dictionary<GroupingValuesKey, IObject>(); foreach (var selection in mySelections) { var attrValue = dbo.Value.GetAttribute(selection.Element, myReferencedDBType, _DBContext); if (attrValue.Failed()) { throw new GraphDBException(attrValue.IErrors); } groupingVals.Add(new GroupingValuesKey(selection.Element, selection.Alias), attrValue.Value); } GroupingKey groupingKey = new GroupingKey(groupingVals); #endregion return groupingKey; }, (dbo) => { CheckLoadedDBObjectStream(dbo, myReferencedDBType); return dbo.Value; }); #endregion foreach (var group in groupedDBOs) { #region Create group readouts var aggregatedAttributes = new Dictionary<String, Object>(); foreach (var aggr in myAggregates) { var aggrResult = aggr.Aggregate.Aggregate(group as IEnumerable<DBObjectStream>, aggr.Element, _DBContext); if (aggrResult.Failed()) { throw new GraphDBException(aggrResult.IErrors); } aggregatedAttributes.Add(aggr.Alias, aggrResult.Value.GetReadoutValue()); } foreach (var groupingKeyVal in group.Key.Values) { aggregatedAttributes.Add(groupingKeyVal.Key.AttributeAlias, groupingKeyVal.Value.GetReadoutValue()); } var dbObjectReadout = new VertexGroup(aggregatedAttributes, (group as IEnumerable<DBObjectStream>).Select(dbo => new Vertex(GetAllSelectedAttributesFromVertex(dbo, myReferencedDBType, -1, null, null, false, true)))); #endregion #region Evaluate having if exist and yield return if (_HavingExpression != null) { var res = _HavingExpression.IsSatisfyHaving(dbObjectReadout, _DBContext); if (res.Failed()) throw new GraphDBException(res.IErrors); else if (res.Value) yield return dbObjectReadout; } else { yield return dbObjectReadout; } #endregion } yield break; #endregion } else { #region No grouping, just aggregates var aggregatedAttributes = new Dictionary<String, Object>(); Vertex _Vertex; if (!myUsingGraph && myAggregates.All(a => a.IndexAggregate != null)) { #region Index aggregates foreach (var aggr in myAggregates) { var idxAggrResult = aggr.Aggregate.Aggregate(aggr.IndexAggregate, myReferencedDBType, _DBContext); if (idxAggrResult.Failed()) { throw new GraphDBException(idxAggrResult.IErrors); } aggregatedAttributes.Add(aggr.Alias, idxAggrResult.Value.GetReadoutValue()); } _Vertex = new Vertex(aggregatedAttributes); #endregion } else { #region OR Attribute aggregates foreach (var aggr in myAggregates) { var curType = _DBContext.DBTypeManager.GetTypeByUUID(aggr.EdgeList.LastEdge.TypeUUID); var curAttr = curType.GetTypeAttributeByUUID(aggr.EdgeList.LastEdge.AttrUUID); var aggrResult = aggr.Aggregate.Aggregate(myDBOs.Select(dbo => { CheckLoadedDBObjectStream(dbo, curType, curAttr); return dbo.Value; }), aggr.Element, _DBContext); if (aggrResult.Failed()) { throw new GraphDBException(aggrResult.IErrors); } aggregatedAttributes.Add(aggr.Alias, aggrResult.Value.GetReadoutValue()); } _Vertex = new Vertex(aggregatedAttributes); #endregion } #region Check having expression and yield return value if (_HavingExpression != null) { var res = _HavingExpression.IsSatisfyHaving(_Vertex, _DBContext); if (res.Failed()) throw new GraphDBException(res.IErrors); else if (res.Value) yield return _Vertex; } else { yield return _Vertex; } #endregion yield break; #endregion } #endregion }
private PlanFile(IEnumerable<Env> environments, IEnumerable<Plan> plans) { _environments = environments.ToLookup(x => x.Name, StringComparer.CurrentCultureIgnoreCase); _plans = plans.ToLookup(x => x.Name, StringComparer.CurrentCultureIgnoreCase); }
private void CheckForItems(IEnumerable<WoWItem> equippableItems) { ILookup<InventoryType, WoWItem> categorizedItems = equippableItems.ToLookup(item => item.ItemInfo.InventoryType); foreach (var grouping in categorizedItems) { if (grouping.Key == InventoryType.Bag) continue; float bestEquipItemScore; WoWItem bestEquipItem = FindBestEquipItem(grouping, out bestEquipItemScore); if (bestEquipItem == null) continue; List<InventorySlot> equipSlots = DecideEquipmentSlots(bestEquipItem); float lowestItemScore; InventorySlot bestSlot = FindBestEquipmentSlot(equipSlots, out lowestItemScore); if (bestSlot == InventorySlot.None) { Log(false, "I'm not equipping item {0} of inventory type {1} as there are no slots to equip it into", bestEquipItem.Name, bestEquipItem.ItemInfo.InventoryType); continue; } if (bestEquipItemScore > lowestItemScore) { if (lowestItemScore == float.MinValue) Log(true, "Equipping {2} \"{0}\" into empty slot {1}", bestEquipItem.Name, bestSlot, bestEquipItem.ItemInfo.InventoryType); else Log(true, "Equipping {4} \"{0}\" instead of \"{1}\" - it scored {2} while the old scored {3}", bestEquipItem.Name, _equippedItems[bestSlot].Name, bestEquipItemScore, lowestItemScore, bestEquipItem.ItemInfo.InventoryType); EquipItemIntoSlot(bestEquipItem, bestSlot); } } }