public void Int(IEnumerable<int> first, IEnumerable<int> second, IEqualityComparer<int> comparer, IEnumerable<int> expected) { if (comparer == null) { Assert.Equal(expected, first.Except(second)); } Assert.Equal(expected, first.Except(second, comparer)); }
public void String(IEnumerable<string> first, IEnumerable<string> second, IEqualityComparer<string> comparer, IEnumerable<string> expected) { if (comparer == null) { Assert.Equal(expected, first.Except(second)); } Assert.Equal(expected, first.Except(second, comparer)); }
/// <summary> /// Initializes a new instance of the <see cref="ClassTypeTree"/> class. /// </summary> /// <param name="types">The types to build the tree out of.</param> public ClassTypeTree(IEnumerable<Type> types) { // ReSharper disable DoNotCallOverridableMethodsInConstructor var childList = new List<ClassTypeTree>(); // Remove duplicates types = types.Where(x => x.IsClass).Distinct(); // Grab the lowest-level types var baseTypes = types.Where(x => !types.Any(y => x != y && y.IsAssignableFrom(x))); // Grab the possible child types var remainingTypes = types.Except(baseTypes); foreach (var bt in baseTypes) { // Recursively build the tree childList.Add(CreateNode(this, bt, remainingTypes)); } // Add the wildcard for the base level childList.Add(CreateNode(this, null, null)); // Store the children _children = FinalizeChildren(childList); // ReSharper restore DoNotCallOverridableMethodsInConstructor }
private static string GatherBucklingLengthsCollection(IEnumerable<BucklingLength> BucklingLengths) { StringBuilder output = new StringBuilder(); IEnumerable<BucklingLength> verticalMembers; IEnumerable<BucklingLength> horizontalMembers; verticalMembers = BucklingLengths.Where(bl => bl.Member.Type == MEMBERTYPE.COLUMN || bl.Member.Type == MEMBERTYPE.POST).OrderBy(bl => bl.Member.StartNode.z).ThenBy(bl => bl.Member.StartNode.x).ThenBy(bl => bl.Member.StartNode.y); horizontalMembers = BucklingLengths.Except(verticalMembers).OrderBy(bl => bl.Member.StartNode.y).ThenBy(bl => bl.Member.StartNode.z).ThenBy(bl => bl.Member.StartNode.x); // Output Columns output.AppendLine("***"); output.AppendLine("*** COLUMNS & POSTS"); output.AppendLine("***"); foreach (BucklingLength bl in verticalMembers) output.AppendLine(bl.ToSTAADString()); // Output beams output.AppendLine("***"); output.AppendLine("*** BEAMS & OTHERS"); output.AppendLine("***"); foreach (IGrouping<double, BucklingLength> bucklingLengthGroup in horizontalMembers.GroupBy(bl => bl.Member.StartNode.y)) { output.AppendLine("***"); output.AppendLine(string.Format("*** EL+{0:0.000}", bucklingLengthGroup.Key)); output.AppendLine("***"); foreach (BucklingLength bl in bucklingLengthGroup) output.AppendLine(bl.ToSTAADString()); } return output.ToString(); }
public void AutoMap(IEnumerable<string> csvColumns) { this.CsvColumns = csvColumns.ToArray(); foreach (var propertyMap in this.PropertyMaps) { var entityColumnName = propertyMap.EntityColumnName; var betterMatchCsvColumn = csvColumns.Select(x => new { csvColumn = x, distance = x.ComputeLevenshteinDistance(entityColumnName) }) .Where(x => x.distance < 2) .OrderBy(x => x.distance) .Select(x => x.csvColumn) .FirstOrDefault(); if (betterMatchCsvColumn != null) { propertyMap.CsvColumnName = betterMatchCsvColumn; propertyMap.CustomValue = null; } else { propertyMap.CsvColumnName = null; } } //All not mapped properties may be a product property this.PropertyCsvColumns = csvColumns.Except(this.PropertyMaps.Where(x => x.CsvColumnName != null).Select(x => x.CsvColumnName)).ToArray(); //Generate ETag for identifying csv format this.ETag = string.Join(";", this.CsvColumns).GetMD5Hash(); }
public IEnumerable<PositionResultsViewModel> GetDetailedItems(long portfolioID, IEnumerable<StockDataItem> items) { try { var results = new List<PositionResultsViewModel>(); var positions = _portRepo.GetAllPositions(portfolioID); if (!positions.Any()) return new List<PositionResultsViewModel>(); var tickers = positions.Select(p => p.Ticker).Distinct(); var stockData = _stockRepo.GetStockQuotes(tickers); foreach (var position in positions) { var ticker = position.Ticker; var tickerStockData = stockData.Single(stock => stock.Ticker == ticker); var stockItems = GetStockItems(items, tickerStockData); var remainingItemsToGet = items.Except(stockItems.Keys); stockItems.AddRange(CalculateItems(remainingItemsToGet, position, tickerStockData)); var positionResults = new PositionResultsViewModel(position.ID ?? -1); positionResults.Items = stockItems; results.Add(positionResults); } return results; } catch (Exception ex) { Log.Error("GetDetailedItems", ex.ToString()); throw; } }
public ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession) { Guard.AgainstNullArgument("references", references); Guard.AgainstNullArgument("scriptPackSession", scriptPackSession); references.PathReferences.UnionWith(scriptPackSession.References); SessionState<Evaluator> sessionState; if (!scriptPackSession.State.ContainsKey(SessionKey)) { Logger.Debug("Creating session"); var context = new CompilerContext(new CompilerSettings { AssemblyReferences = references.PathReferences.ToList() }, new ConsoleReportPrinter()); var evaluator = new Evaluator(context); var allNamespaces = namespaces.Union(scriptPackSession.Namespaces).Distinct(); var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts), scriptArgs); MonoHost.SetHost((ScriptHost)host); evaluator.ReferenceAssembly(typeof(MonoHost).Assembly); evaluator.InteractiveBaseClass = typeof(MonoHost); sessionState = new SessionState<Evaluator> { References = new AssemblyReferences(references.PathReferences, references.Assemblies), Namespaces = new HashSet<string>(), Session = evaluator }; ImportNamespaces(allNamespaces, sessionState); scriptPackSession.State[SessionKey] = sessionState; } else { Logger.Debug("Reusing existing session"); sessionState = (SessionState<Evaluator>)scriptPackSession.State[SessionKey]; var newReferences = sessionState.References == null ? references : references.Except(sessionState.References); foreach (var reference in newReferences.PathReferences) { Logger.DebugFormat("Adding reference to {0}", reference); sessionState.Session.LoadAssembly(reference); } sessionState.References = new AssemblyReferences(references.PathReferences, references.Assemblies); var newNamespaces = sessionState.Namespaces == null ? namespaces : namespaces.Except(sessionState.Namespaces); ImportNamespaces(newNamespaces, sessionState); } Logger.Debug("Starting execution"); var result = Execute(code, sessionState.Session); Logger.Debug("Finished execution"); return result; }
public void UpdateSession(IEnumerable<EventSourceSettings> updatedEventSources) { Guard.ArgumentNotNull(updatedEventSources, "updatedEventSources"); var eventSourceComparer = new EventSourceSettingsEqualityComparer(nameOnly: true); // updated sources foreach (var currentSource in this.eventSources.Intersect(updatedEventSources, eventSourceComparer).ToArray()) { var updatedSource = updatedEventSources.Single(s => s.Name == currentSource.Name); if (updatedSource.Level != currentSource.Level || updatedSource.MatchAnyKeyword != currentSource.MatchAnyKeyword) { TraceEventUtil.EnableProvider(this.session, updatedSource.EventSourceId, updatedSource.Level, updatedSource.MatchAnyKeyword, sendManifest: false); currentSource.Level = updatedSource.Level; currentSource.MatchAnyKeyword = updatedSource.MatchAnyKeyword; } } // new sources foreach (var newSource in updatedEventSources.Except(this.eventSources, eventSourceComparer).ToArray()) { TraceEventUtil.EnableProvider(this.session, newSource.EventSourceId, newSource.Level, newSource.MatchAnyKeyword, sendManifest: true); this.eventSources.Add(newSource); } // removed sources foreach (var removedSource in this.eventSources.Except(updatedEventSources, eventSourceComparer).ToArray()) { this.session.DisableProvider(removedSource.EventSourceId); this.eventSources.Remove(removedSource); } }
private static async Task<SimpleHttpResponse> DoForContainersAsync(string container, HttpStatusCode successStatus, Func<CloudBlobContainer, Task> action, IEnumerable<CloudStorageAccount> accounts, bool ignoreNotFound, IEnumerable<CloudStorageAccount> excludeAccounts) { SimpleHttpResponse retval = new SimpleHttpResponse { StatusCode = successStatus, }; if (excludeAccounts != null) { accounts = accounts.Except(excludeAccounts); } var actionTasks = accounts .Select(account => action(NamespaceHandler.GetContainerByName(account, container))); try { await Task.WhenAll(actionTasks.ToArray()); } catch (AggregateException aggEx) { aggEx.Handle(ex => ProcessException(ex, ignoreNotFound, retval)); } catch (Exception ex) { if (!ProcessException(ex, ignoreNotFound, retval)) { throw; } } return retval; }
private IEnumerable<Attribute> FilterAttributes( IEnumerable<Attribute> attributes, string validationRule) { var validatorAttributes = attributes.OfType<ValidatorAttribute>(); var nonValidatorAttributes = attributes.Except(validatorAttributes); List<ValidatorAttribute> validValidatorAttributes = new List<ValidatorAttribute>(); if (string.IsNullOrEmpty(validationRule)) { validValidatorAttributes.AddRange(validatorAttributes.Where(v => string.IsNullOrEmpty(v.RuleName))); } else { var groups = from validator in validatorAttributes group validator by validator.GetType(); foreach (var group in groups) { ValidatorAttribute validatorAttribute = group.Where(v => string.Compare(v.RuleName, validationRule, true) == 0).FirstOrDefault(); if (null != validatorAttribute) { validValidatorAttributes.Add(validatorAttribute); } else { validatorAttribute = group.Where(v => string.IsNullOrEmpty(v.RuleName)).FirstOrDefault(); if (null != validatorAttribute) { validValidatorAttributes.Add(validatorAttribute); } } } } return nonValidatorAttributes.Union(validValidatorAttributes); }
public string[] GetFilenamesNotInCache(IEnumerable<string> filenamesToCheck) { var filenamesInCache = ListFiles().Select(fi => fi.Name); var filenamesNotInCache = filenamesToCheck.Except(filenamesInCache); return filenamesNotInCache.ToArray(); }
public List<GameObject> Build(IEnumerable<GameObject> gameObjects) { if (IsCompleted) return gameObjects.ToList(); var availableObjects = new List<GameObject>(); foreach (var buildItem in BuildItems) { if (_percentLeftToBuild <= 0) break; var percentPerBuild = Math.Min(_percentLeftToBuild, PercentPerAction); var buildItemCount = percentPerBuild / buildItem.PercentPerItem; buildItemCount = (buildItemCount * buildItem.PercentPerItem) < percentPerBuild ? buildItemCount + 1 : buildItemCount; var buildItemAVObjects = gameObjects.Where(lgo => buildItem.CheckObject(lgo)).Take(buildItemCount).ToList(); availableObjects.AddRange(buildItemAVObjects); buildItem.CountUsedToBuild += buildItemAVObjects.Count; _percentLeftToBuild = _percentLeftToBuild - buildItemAVObjects.Count * buildItem.PercentPerItem; } availableObjects.ForEach(go => go.RemoveFromContainer()); return gameObjects.Except(availableObjects).ToList(); }
public virtual void Execute(int userId, int vehicleId, IEnumerable<FillupEntry> importedFillups) { if (importedFillups == null) throw new ArgumentNullException("importedFillups"); try { Vehicle vehicle = _vehicleRepository.GetVehicle(userId, vehicleId); if (vehicle != null) { foreach (FillupEntry newFillup in importedFillups) { newFillup.VehicleId = vehicleId; } // Import all fillups, ignoring duplicates foreach (FillupEntry newFillup in importedFillups.Except(vehicle.Fillups)) { AdjustSurroundingFillupEntries(newFillup); _fillupRepository.Create(userId, vehicleId, newFillup); } } } catch (InvalidOperationException ex) { throw new BusinessServicesException(Resources.UnableToAddFillupToVehicleExceptionMessage, ex); } }
public async Task UpdateEndpointSubscriptions(string endpoint, IEnumerable<Subscription> subscriptions) { // lazy initialization, ensures only one thread runs the initialize function await this.initializationTask.Value; var storedSubscriptions = await this.store.GetByEndpoint(endpoint); var subscriptionsToAdd = subscriptions.Except(storedSubscriptions); var subscriptionsToRemove = storedSubscriptions.Except(subscriptions); var tasks = new List<Task>(); foreach (var subscription in subscriptionsToAdd) { tasks.Add(this.AddSubscription(subscription)); } foreach (var subscription in subscriptionsToRemove) { tasks.Add(this.RemoveSubscription(subscription)); } if (tasks.Count > 0) { await Task.WhenAll(tasks.ToArray()); } }
private void GetNextSteps(Stack<Node> currentChain, IEnumerable<Node> greyList, Node currentNode) { currentChain.Push(currentNode); var newGreyList = greyList .Except(currentNode.Antecedents()) .Except(currentNode.Descendents()) .Distinct(); if (newGreyList.Count() == 0) { ConcurrencyChains.Add(currentChain.ToList()); MaxConcurrency = Math.Max(MaxConcurrency, (int) currentChain.Count); } foreach (var newPossible in newGreyList) { if (_previouslySeenRoots.Contains(newPossible)) continue; GetNextSteps(currentChain, newGreyList, newPossible); } currentChain.Pop(); }
public IEnumerable<Card> Match(IEnumerable<Card> cardsToMatch) { var nofAKind = new NofAKind(); var threeOfAKind = nofAKind.Find(cardsToMatch, 3); if (threeOfAKind != null) { var restOfTheCards = cardsToMatch.Except(threeOfAKind); IEnumerable<Card> currentPair, highestPair = null; while ((currentPair = nofAKind.Find(restOfTheCards, 2)) != null) { if (highestPair == null || currentPair.First().Rank > highestPair.First().Rank) { highestPair = currentPair; restOfTheCards = restOfTheCards.Except(currentPair); } } return highestPair != null ? threeOfAKind.Union(highestPair) : null; } return null; }
/// <summary> /// Determines whether the given folder contains only the given files, and no others /// </summary> /// <returns></returns> protected bool FolderContainsExclusive(string relFolderPath, IEnumerable<string> filenames, Anomalies anomalies = null) { var dirPath = Path.Combine(this.TargetDir, relFolderPath); var exists = Directory.Exists(dirPath); if (!exists) { return false; } else { var folderFiles = new DirectoryInfo(dirPath).GetFiles(); var filesInFolder = folderFiles.Select(f => f.Name).Except(filenames).ToList(); var expectedFiles = filenames.Except(folderFiles.Select(f => f.Name)).ToList(); if (anomalies != null) { anomalies.ExpectedFiles.AddRange(expectedFiles); anomalies.UnexpectedFiles.AddRange(filesInFolder); } return !(filesInFolder.Any()) && !(expectedFiles.Any()); } }
static Types() { BuiltIn = new[] { typeof (Boolean), typeof (Byte), typeof (SByte), typeof (Char), typeof (Single), typeof (Double), typeof (Decimal), typeof (Int16), typeof (Int32), typeof (Int64), typeof (UInt16), typeof (UInt32), typeof (UInt64), typeof (String), typeof (Object) }; Simple = BuiltIn.Except(new[] { typeof(String), typeof(Object) }).ToArray(); Comparable = Simple.Except(new[] { typeof(Boolean) }).ToArray(); Empty = Enumerable.Empty<Type>(); }
/// <summary> /// Obtain the set between two lists /// </summary> /// <param name="before"></param> /// <param name="after"></param> /// <returns>List of Unique Application Names</returns> public static List<string> GetAppsToDelete(IEnumerable<string> before, IEnumerable<string> after) { var applicationNames = before.Except(after); var enumerable = applicationNames as IList<string> ?? applicationNames.ToList(); return enumerable.Any() ? enumerable.ToList() : null; }
public MergeWritingSystemDlg(FdoCache cache, IWritingSystem ws, IEnumerable<IWritingSystem> wss, IHelpTopicProvider helpTopicProvider) { m_cache = cache; m_ws = ws; // // Required for Windows Form Designer support // InitializeComponent(); Icon infoIcon = SystemIcons.Information; m_infoPictureBox.Image = infoIcon.ToBitmap(); m_infoPictureBox.Size = infoIcon.Size; foreach (IWritingSystem curWs in wss.Except(new[] { ws })) m_wsListBox.Items.Add(curWs); m_wsListBox.SelectedIndex = 0; m_helpTopicProvider = helpTopicProvider; if (m_helpTopicProvider != null) // m_helpTopicProvider could be null for testing { m_helpProvider = new HelpProvider(); m_helpProvider.HelpNamespace = m_helpTopicProvider.HelpFile; m_helpProvider.SetHelpKeyword(this, m_helpTopicProvider.GetHelpString(HelpTopic)); m_helpProvider.SetHelpNavigator(this, HelpNavigator.Topic); } }
/// <summary> /// Compares two sets of formal attributes. /// </summary> /// <param name="setA">The first set to compare.</param> /// <param name="setB">The second set to compare.s</param> /// <returns>True, if both sets contain the same elements. Otherwise return false.</returns> public static bool SetEquals(this IEnumerable<Attribute> setA, IEnumerable<Attribute> setB) { var AnotB = setA.Except(setB); var BnotA = setB.Except(setA); return ((AnotB == null || !AnotB.Any()) && (BnotA == null || !BnotA.Any())); }
protected async Task ProcessDifferences(IEnumerable<Champion> itemsFromApi, IEnumerable<Champion> itemsFromCollection) { var itemsDifferentFromDb = itemsFromApi.Except(itemsFromCollection); int itemsDifferentFromDbCount = itemsDifferentFromDb.Count(); var itemsMissingFromApi = itemsFromCollection.Except(itemsFromApi); if (itemsDifferentFromDbCount > 0) { var itemsDifferentThanApi = itemsMissingFromApi.Where(c => itemsDifferentFromDb.All(i => i.ChampionId == c.ChampionId)); itemsMissingFromApi = itemsMissingFromApi.Except(itemsDifferentThanApi); } var itemsMissingFromApiCount = itemsMissingFromApi.Count(); if (itemsDifferentFromDbCount > 0) { this.logger.InfoFormat("Champions different in database count: {0}", itemsDifferentFromDbCount); await this.ProcessItemsMissingFromDb(itemsDifferentFromDb); } if (itemsMissingFromApiCount > 0) { this.logger.InfoFormat("Champions missing from API count: {0}", itemsMissingFromApiCount); await this.ProcessItemsMissingFromApi(itemsMissingFromApi); } }
private IEnumerable<EmployeeLogin> SRVCUpdateLogins(Helpers.Log.SessionInfo logSession, Repository.Logic.Repository rep, long employeeId, IEnumerable<string> addLogins, IEnumerable<string> removeLogins) { #pragma warning disable 618 logSession.Add($"Try to get employee with id = {employeeId}"); var emp = rep.Get<Repository.Model.Employee>(e => e.EmployeeId == employeeId, false, new string[] { "Logins" }).FirstOrDefault(); if (emp == null) throw new Exception(string.Format(Properties.Resources.STUFFINGSERVICE_EmployeeNotFound, employeeId)); var existedLogins = emp.Logins.Select(r => r.DomainLogin); #region Add logins if (addLogins != null && addLogins.Any()) { logSession.Add($"Add logins..."); var addLoginsUpper = addLogins .Except(existedLogins) .ToArray() .Select(r => rep.New<Repository.Model.EmployeeLogin>((er) => { er.EmployeeLoginId = emp.EmployeeId; er.DomainLogin = r; })) .ToArray(); logSession.Add($"Add this logins {addLoginsUpper.Concat(r => r.DomainLogin, ",")} for employee id = {employeeId}"); foreach (var r in addLoginsUpper) emp.Logins.Add(r); rep.AddRange(addLoginsUpper, saveAfterInsert: false); } #endregion #region Remove rights if (removeLogins != null && removeLogins.Any()) { logSession.Add($"Remove logins..."); var removeLoginsUpper = removeLogins .Intersect(existedLogins) .ToArray() .Join(emp.Logins, r => r, er => er.DomainLogin.ToUpper(), (r, er) => er) .ToArray(); logSession.Add($"Remove this logins {removeLoginsUpper.Concat(r => r.DomainLogin, ",")} for employee id = {employeeId}"); foreach (var r in removeLoginsUpper) emp.Logins.Remove(r); rep.RemoveRange(removeLoginsUpper, saveAfterRemove: false); } #endregion rep.SaveChanges(); return emp.Logins.Select(er => AutoMapper.Mapper.Map<EmployeeLogin>(er)); #pragma warning restore 618 }
static IEnumerable<int[]> Crossover(IEnumerable<int> father, IEnumerable<int> mother) { IEnumerable<int> intersect = father.Intersect(mother), motherRest = mother.Except(intersect), fatherRest = father.Except(intersect); int motherRestHalfSize = motherRest.Count() / 2, fatherRestRestHalfSize = fatherRest.Count() / 2; yield return intersect.Concat(motherRest.Take(motherRestHalfSize)).Concat(fatherRest.Skip(fatherRestRestHalfSize)).ToArray(); yield return intersect.Concat(motherRest.Skip(motherRestHalfSize)).Concat(fatherRest.Take(fatherRestRestHalfSize)).ToArray(); }
public IEnumerable<string> FilesToDelete(IEnumerable<string> duplicates) { var keep = duplicates .FirstOrDefault(x => InPath(_keepDirectory, x)) ?? duplicates.Last(); return duplicates.Except(new[] { keep }); }
private static void ShowDuplicateClothes(IEnumerable<ClothingArticle> clothes, IEnumerable<ClothingArticle> newClothes) { var duplicatedClothes = clothes.Except(newClothes); foreach (var clothingArticle in duplicatedClothes) { Console.WriteLine("Found duplicate clothing article: {0}.", clothingArticle); } }
public void Check(IEnumerable<IComponent> components, IStore<string, IArtificialIntelligence> aiStore) { var groupedByOwener = components.GroupBy(x => x.OwnerId); foreach (var group in groupedByOwener) { var enemies = components.Except(group).OfType<IFieldOfVision>(); foreach (var component in group) { foreach (var enemy in enemies) { var isInFieldOfVision = enemy.IsInFieldOfVision(component.Position); if (isInFieldOfVision) { var artificialIntelligence = aiStore.Get(enemy.OwnerId); artificialIntelligence.Fire(new ComponentSpottedEvent(enemy.OwnerId, enemy.Id, component.Id, component.OwnerId, component.Position.X, component.Position.Y, component.GetType())); SpottedUnitsStore.Store(component.Id, enemy.OwnerId); } } } } //foreach (var group in groupedByOwener) { // var others = components.Except(group).OfType<IFieldOfVision>(); // foreach (var component in group) { // var spottingUnits = others.Where(x => x.IsInFieldOfVision(component.Position)); // foreach (var fieldOfVision in spottingUnits) { // var artificialIntelligence = aiStore.Get(fieldOfVision.OwnerId); // artificialIntelligence.Fire(new ComponentSpottedEvent(fieldOfVision.OwnerId,fieldOfVision.Id,component.Id,component.OwnerId,component.Position.X,component.Position.Y, component.GetType())); // SpottedUnitsStore.Store(component.Id,fieldOfVision.OwnerId); // } // } //} var spottedUnits = SpottedUnitsStore.GetKeys(); Parallel.ForEach(spottedUnits, (suid,loopState) => { var spottedComponent = components.SingleOrDefault(x => x.Id.Equals(suid)); if(spottedComponent == null) { SpottedUnitsStore.Remove(suid); } else { var enemyOwnerId = SpottedUnitsStore.Get(suid); if(enemyOwnerId == null) return; var enemyUnits = components.Where(x => x.OwnerId.Equals(enemyOwnerId)).OfType<IFieldOfVision>(); if(enemyUnits.All(x => !x.IsInFieldOfVision(spottedComponent.Position))) { SpottedUnitsStore.Remove(spottedComponent.Id); var artificialIntelligence = aiStore.Where(x => x.Id.Equals(enemyOwnerId)).First(); artificialIntelligence.Fire(new ComponentLeftFieldOfVisionEvent(artificialIntelligence.Id,spottedComponent.Id,spottedComponent.OwnerId,spottedComponent.Position.X,spottedComponent.Position.Y,spottedComponent.GetType())); } } }); }
public void AddValues(Category category, IEnumerable<CategoryValue> values) { if (!_categoryCache.ContainsKey(category.Name)) throw new CategoryNotFoundException(string.Format("Category '{0}' not found.", category.Name)); var tempValues = new List<CategoryValue>(category.Values); tempValues.AddRange(values.Except(category.Values)); category.Values = tempValues; }
public Inputs(IEnumerable<string> filesOrStandardInput) { var fileNames = new Glob(Environment.CurrentDirectory); filesOrStandardInput.Except(Input.IsStandardInput).Each(fileNames.Include); inputs = fileNames.Select(f => new Input(f)).ToList(); if (filesOrStandardInput.Any(Input.IsStandardInput) || inputs.Count == 0) inputs.Insert(0, Input.FromStandardInput()); }
private void AnalyzeSymbol(SymbolAnalysisContext symbolContext, IEnumerable<INamedTypeSymbol> exportAttributes) { var namedType = (INamedTypeSymbol)symbolContext.Symbol; var namedTypeAttributes = AttributeHelpers.GetApplicableAttributes(namedType); // Figure out which export attributes are being used here var appliedExportAttributes = exportAttributes.Where(e => namedTypeAttributes.Any(ad => AttributeHelpers.DerivesFrom(ad.AttributeClass, e))).ToList(); // If we have no exports we're done if (appliedExportAttributes.Count == 0) { return; } var badNamespaces = exportAttributes.Except(appliedExportAttributes).Select(s => s.ContainingNamespace).ToList(); // Now look at all attributes and see if any are metadata attributes foreach (var namedTypeAttribute in namedTypeAttributes) { if (AttributeHelpers.GetApplicableAttributes(namedTypeAttribute.AttributeClass).Any(ad => badNamespaces.Contains(ad.AttributeClass.ContainingNamespace) && ad.AttributeClass.Name == "MetadataAttributeAttribute")) { ReportDiagnostic(symbolContext, namedType, namedTypeAttribute); } } // Also look through all members and their attributes, and see if any are using from bad places foreach (var member in namedType.GetMembers()) { foreach (var attribute in member.GetAttributes()) { if (badNamespaces.Contains(attribute.AttributeClass.ContainingNamespace)) { ReportDiagnostic(symbolContext, namedType, attribute); } } // if it's a constructor, we should also check parameters since they may have [ImportMany] var methodSymbol = member as IMethodSymbol; if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.Constructor) { foreach (var parameter in methodSymbol.Parameters) { foreach (var attribute in parameter.GetAttributes()) { if (badNamespaces.Contains(attribute.AttributeClass.ContainingNamespace)) { ReportDiagnostic(symbolContext, namedType, attribute); } } } } } }
public static CSharpCompilation CreateStandardCompilation( IEnumerable <SyntaxTree> trees, IEnumerable <MetadataReference> references = null, CSharpCompilationOptions options = null, string assemblyName = "") { if (CoreClrShim.IsRunningOnCoreClr) { references = references?.Except(s_desktopRefsToRemove); } return(CreateCompilation(trees, (references != null) ? s_stdRefs.Concat(references) : s_stdRefs, options, assemblyName)); }
/// <summary> /// Add or update the identity roles /// </summary> /// <param name="groups">The groups to updates</param> /// <param name="identityMember">The member as an identity user</param> private async Task <ActionResult <bool> > AddOrUpdateRoles(IEnumerable <string>?groups, MemberIdentityUser identityMember) { var hasChanges = false; // We're gonna look up the current roles now because the below code can cause // events to be raised and developers could be manually adding roles to members in // their handlers. If we don't look this up now there's a chance we'll just end up // removing the roles they've assigned. IEnumerable <string> currentRoles = await _memberManager.GetRolesAsync(identityMember); // find the ones to remove and remove them IEnumerable <string> roles = currentRoles.ToList(); var rolesToRemove = roles.Except(groups ?? Enumerable.Empty <string>()).ToArray(); // Now let's do the role provider stuff - now that we've saved the content item (that is important since // if we are changing the username, it must be persisted before looking up the member roles). if (rolesToRemove.Any()) { IdentityResult identityResult = await _memberManager.RemoveFromRolesAsync(identityMember, rolesToRemove); if (!identityResult.Succeeded) { return(ValidationProblem(identityResult.Errors.ToErrorMessage())); } hasChanges = true; } // find the ones to add and add them var toAdd = groups?.Except(roles).ToArray(); if (toAdd?.Any() ?? false) { // add the ones submitted IdentityResult identityResult = await _memberManager.AddToRolesAsync(identityMember, toAdd); if (!identityResult.Succeeded) { return(ValidationProblem(identityResult.Errors.ToErrorMessage())); } hasChanges = true; } return(hasChanges); }
/// <summary> /// Authorize that the user is not adding a section to the group that they don't have access to /// </summary> public Attempt <string?> AuthorizeSectionChanges( IUser?currentUser, IEnumerable <string>?existingSections, IEnumerable <string>?proposedAllowedSections) { if (currentUser?.IsAdmin() ?? false) { return(Attempt <string?> .Succeed()); } var sectionsAdded = proposedAllowedSections?.Except(existingSections ?? Enumerable.Empty <string>()).ToArray(); var sectionAccessMissing = sectionsAdded?.Except(currentUser?.AllowedSections ?? Enumerable.Empty <string>()).ToArray(); return(sectionAccessMissing?.Length > 0 ? Attempt.Fail("Current user doesn't have access to add these sections " + string.Join(", ", sectionAccessMissing)) : Attempt <string?> .Succeed()); }
public async Task <IList <T> > LoadSomeAsync <T>(IEnumerable <Guid> ids = null, Expression <Func <T, bool> > predicate = null, int?skip = null, int?take = null, string orderBy = null, string orderMode = null) where T : EntityBase { var tracked = _dbContext.ChangeTracker.Entries <T>() .Where(e => ids == null || ids.Contains(e.Entity.Id)) .Where(e => predicate == null || predicate.Compile()(e.Entity)) .Select(e => e.Entity) .ToList(); var idsToTrack = ids?.Except(tracked.Select(e => e.Id)).ToList(); var toTrack = new List <T>(); if (idsToTrack?.Count != 0) { var set = _dbContext.Set <T>().AsQueryable() .Where(e => idsToTrack.Contains(e.Id)); if (predicate != null) { set = set.Where(predicate); } toTrack = await set.ToListAsync(); } tracked.AddRange(toTrack); var query = tracked.AsQueryable(); if (orderBy != null) { query = query.OrderBy($"{orderBy} {NormalizeOrderMode(orderMode)}"); } else { query = query.OrderBy(s => s.Name); } if (!skip.HasValue && !take.HasValue) { return(query.ToList()); } else { return(query.Skip(skip ?? 0).Take(take ?? tracked.Count).ToList()); } }
private static string BuildMessage( [NotNull] IEnumerable <object> superset, IEnumerable <object>?valuesThatShouldBeThere, string?messagePrefix ) { PrettificationSettings prettySettings = new PrettificationSettings() { TypeLabelStyle = { Value = TypeNameStyle.Full } }; var badValues = valuesThatShouldBeThere?.Except(superset); return(new Dictionary <object, object>() { [superset.GetType().PrettifyType(prettySettings)] = superset, [nameof(valuesThatShouldBeThere)] = valuesThatShouldBeThere, ["Disallowed values"] = badValues }.Prettify(prettySettings) .SplitLines() .PrependNonNull(messagePrefix) .JoinLines()); }
/// <summary> /// Delete old rows for the specified table, checkpoint and simulation. /// </summary> /// <param name="tableName">The table name to delete from.</param> /// <param name="checkpointName">The checkpoint name to use to match rows to delete.</param> /// <param name="simulationNamesThatMayNeedCleaning">Simulation names that may need cleaning up.</param> private void DeleteOldRowsInTable(string tableName, string checkpointName = null, IEnumerable <string> simulationNamesThatMayNeedCleaning = null) { // Can be called by many threads simultaneously. List <int> simulationIds = null; if (tablesNotNeedingIndexColumns.Contains(tableName)) { // Create a delete row command to remove the rows. lock (lockObject) { // This will drop the table. commands.Add(new DeleteRowsCommand(Connection, tableName, 0, simulationIds)); } } else { if (simulationNamesThatMayNeedCleaning != null) { IEnumerable <string> simsNeedingCleaning; lock (lockObject) { // Have we written anything to this table yet? if (!simulationNamesThatHaveBeenCleanedUp.TryGetValue(tableName, out var simsThatHaveBeenCleanedUp)) { // No - create a empty list of simulation names that we've cleaned up. simulationNamesThatHaveBeenCleanedUp.Add(tableName, new List <string>()); simsNeedingCleaning = simulationNamesThatMayNeedCleaning; } else { // Get a list of simulations that haven't been cleaned up for this table. simsNeedingCleaning = simulationNamesThatMayNeedCleaning.Except(simsThatHaveBeenCleanedUp); } simulationIds = new List <int>(); if (simsNeedingCleaning.Any()) { // Add the simulations we're about to clean to our list so // that they aren't cleaned again. Also get id's for each one. foreach (var simulationName in simsNeedingCleaning) { simulationNamesThatHaveBeenCleanedUp[tableName].Add(simulationName); simulationIds.Add(GetSimulationID(simulationName, null)); } } } } if (simulationNamesThatMayNeedCleaning == null || simulationIds.Any()) { // Get a checkpoint id. var checkpointID = 0; if (checkpointName != null) { checkpointID = GetCheckpointID(checkpointName); } // Create a delete row command to remove the rows. lock (lockObject) { commands.Add(new DeleteRowsCommand(Connection, tableName, checkpointID, simulationIds)); } } } }
public static IEnumerable <TSource> Except <TSource>(this IEnumerable <TSource> first, IEnumerable <TSource> second, Func <TSource, object> fieldSelector) { return(first.Except(second, new GenericEqualityComparer <TSource>(fieldSelector))); }
public static bool IsSubset <T>(this IEnumerable <T> thisEnumerable, IEnumerable <T> other) { return(!thisEnumerable.Except(other).Any()); }
private async Task ImportInternalAsync(Channel <ImportResource> inputChannel, Channel <ImportProcessingProgress> outputChannel, IImportErrorStore importErrorStore, CancellationToken cancellationToken) { try { _logger.LogInformation("Start to import data to SQL data store."); Task <ImportProcessingProgress> checkpointTask = Task.FromResult <ImportProcessingProgress>(null); long succeedCount = 0; long failedCount = 0; long?lastCheckpointIndex = null; long currentIndex = -1; Dictionary <string, DataTable> resourceParamsBuffer = new Dictionary <string, DataTable>(); List <string> importErrorBuffer = new List <string>(); Queue <Task <ImportProcessingProgress> > importTasks = new Queue <Task <ImportProcessingProgress> >(); List <ImportResource> resourceBuffer = new List <ImportResource>(); await _sqlBulkCopyDataWrapperFactory.EnsureInitializedAsync(); await foreach (ImportResource resource in inputChannel.Reader.ReadAllAsync(cancellationToken)) { if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(); } lastCheckpointIndex = lastCheckpointIndex ?? resource.Index - 1; currentIndex = resource.Index; resourceBuffer.Add(resource); if (resourceBuffer.Count < _importTaskConfiguration.SqlBatchSizeForImportResourceOperation) { continue; } try { // Handle resources in buffer IEnumerable <ImportResource> resourcesWithError = resourceBuffer.Where(r => r.ContainsError()); IEnumerable <SqlBulkCopyDataWrapper> inputResources = resourceBuffer.Where(r => !r.ContainsError()).Select(r => _sqlBulkCopyDataWrapperFactory.CreateSqlBulkCopyDataWrapper(r)); IEnumerable <SqlBulkCopyDataWrapper> mergedResources = await _sqlImportOperation.BulkMergeResourceAsync(inputResources, cancellationToken); IEnumerable <SqlBulkCopyDataWrapper> duplicateResourcesNotMerged = inputResources.Except(mergedResources); importErrorBuffer.AddRange(resourcesWithError.Select(r => r.ImportError)); await FillResourceParamsBuffer(mergedResources.ToArray(), resourceParamsBuffer); AppendDuplicatedResouceErrorToBuffer(duplicateResourcesNotMerged, importErrorBuffer); succeedCount += mergedResources.Count(); failedCount += resourcesWithError.Count() + duplicateResourcesNotMerged.Count(); } finally { foreach (ImportResource importResource in resourceBuffer) { importResource?.CompressedStream?.Dispose(); } resourceBuffer.Clear(); } bool shouldCreateCheckpoint = resource.Index - lastCheckpointIndex >= _importTaskConfiguration.SqlImportBatchSizeForCheckpoint; if (shouldCreateCheckpoint) { // Create checkpoint for all tables not empty string[] tableNameNeedImport = resourceParamsBuffer.Where(r => r.Value.Rows.Count > 0).Select(r => r.Key).ToArray(); foreach (string tableName in tableNameNeedImport) { DataTable dataTable = resourceParamsBuffer[tableName]; resourceParamsBuffer.Remove(tableName); await EnqueueTaskAsync(importTasks, () => ImportDataTableAsync(dataTable, cancellationToken), outputChannel); } // wait previous checkpoint task complete await checkpointTask; // upload error logs for import errors string[] importErrors = importErrorBuffer.ToArray(); importErrorBuffer.Clear(); lastCheckpointIndex = resource.Index; checkpointTask = await EnqueueTaskAsync(importTasks, () => UploadImportErrorsAsync(importErrorStore, succeedCount, failedCount, importErrors, currentIndex, cancellationToken), outputChannel); } else { // import table >= MaxResourceCountInBatch string[] tableNameNeedImport = resourceParamsBuffer.Where(r => r.Value.Rows.Count >= _importTaskConfiguration.SqlBatchSizeForImportParamsOperation).Select(r => r.Key).ToArray(); foreach (string tableName in tableNameNeedImport) { DataTable dataTable = resourceParamsBuffer[tableName]; resourceParamsBuffer.Remove(tableName); await EnqueueTaskAsync(importTasks, () => ImportDataTableAsync(dataTable, cancellationToken), outputChannel); } } } try { // Handle resources in buffer IEnumerable <ImportResource> resourcesWithError = resourceBuffer.Where(r => r.ContainsError()); IEnumerable <SqlBulkCopyDataWrapper> inputResources = resourceBuffer.Where(r => !r.ContainsError()).Select(r => _sqlBulkCopyDataWrapperFactory.CreateSqlBulkCopyDataWrapper(r)); IEnumerable <SqlBulkCopyDataWrapper> mergedResources = await _sqlImportOperation.BulkMergeResourceAsync(inputResources, cancellationToken); IEnumerable <SqlBulkCopyDataWrapper> duplicateResourcesNotMerged = inputResources.Except(mergedResources); importErrorBuffer.AddRange(resourcesWithError.Select(r => r.ImportError)); await FillResourceParamsBuffer(mergedResources.ToArray(), resourceParamsBuffer); AppendDuplicatedResouceErrorToBuffer(duplicateResourcesNotMerged, importErrorBuffer); succeedCount += mergedResources.Count(); failedCount += resourcesWithError.Count() + duplicateResourcesNotMerged.Count(); } finally { foreach (ImportResource importResource in resourceBuffer) { importResource?.CompressedStream?.Dispose(); } resourceBuffer.Clear(); } // Import all remain tables string[] allTablesNotNull = resourceParamsBuffer.Where(r => r.Value.Rows.Count > 0).Select(r => r.Key).ToArray(); foreach (string tableName in allTablesNotNull) { DataTable dataTable = resourceParamsBuffer[tableName]; await EnqueueTaskAsync(importTasks, () => ImportDataTableAsync(dataTable, cancellationToken), outputChannel); } // Wait all table import task complete while (importTasks.Count > 0) { await importTasks.Dequeue(); } // Upload remain error logs ImportProcessingProgress progress = await UploadImportErrorsAsync(importErrorStore, succeedCount, failedCount, importErrorBuffer.ToArray(), currentIndex, cancellationToken); await outputChannel.Writer.WriteAsync(progress, cancellationToken); } finally { outputChannel.Writer.Complete(); _logger.LogInformation("Import data to SQL data store complete."); } }
public static IEnumerable <T> Except <T>(this IEnumerable <T> list, T item) { return(list.Except(item.Yield())); }
public static IEnumerable <T> ExceptSingle <T>(this IEnumerable <T> sequence, T addition) { return(sequence.Except(new T[] { addition })); }
public static IEnumerable <Presence> CalculateFlightTimes(this IEnumerable <Presence> presences, Block block, Worker worker) { int iterationIndex = 0; if (presences.Count() == 0) { Presence presence = new Presence(block.Start, block.End); presence.FlightTime = block.End - block.Start; presences = presences.Concat(new[] { presence }); } else { IEnumerable <Presence> absentAfterOneBlockEndPresences = presences.Where(p => p.Arrival > block.End); IEnumerable <Presence> absentBeforeOneBlockStartPresences = presences.Where(p => p.Departure < block.Start); presences = presences.Except(absentAfterOneBlockEndPresences).Except(absentBeforeOneBlockStartPresences); foreach (Presence presence in presences) { if (iterationIndex == 0) { presence.FlightTime = presence.Arrival > block.Start ? presence.Arrival - block.Start : TimeSpan.Zero; if (iterationIndex == presences.Count() - 1) { presence.FlightTime += presence.Departure < block.End ? block.End - presence.Departure : TimeSpan.Zero; } } else { presence.FlightTime = presence.Arrival - presences.ElementAt(iterationIndex - 1).Departure; if (iterationIndex == presences.Count() - 1) { presence.FlightTime += presence.Departure < block.End ? block.End - presence.Departure : TimeSpan.Zero; } } iterationIndex++; } worker.blocksWorked.Add(block); // Calculating arrival after block ends if (absentAfterOneBlockEndPresences.Count() > 0) { // If there are no presences related to current block if (presences.Where(p => (p.Arrival >= block.Start || p.Arrival <= block.End) || (p.Departure >= block.Start || p.Departure <= block.End)).Count() == 0) { Presence firstPresence = absentAfterOneBlockEndPresences.ElementAt(0); firstPresence.FlightTime = firstPresence.Arrival - block.End; presences = presences.Concat(new[] { firstPresence }); // Remove the block from worked blocks because worker is absent if (worker.blocksWorked.Contains(block)) { worker.blocksWorked.Remove(block); } } } // Calculating departure before block starts (**This may not be needed**. If it is not needed, this code part can be safely disabled) // See last presence (new Presence(new DateTime(1899, 12, 6, 8, 0, 0), new DateTime(1899, 12, 6, 12, 59, 0))) // Ex. 08:00 - 12:59 if (absentBeforeOneBlockStartPresences.Count() > 0) { // If there are no presences related to current block if (presences.Where(p => (p.Arrival >= block.Start || p.Arrival <= block.End) || (p.Departure >= block.Start || p.Departure <= block.End)).Count() == 0) { Presence lastPresence = absentBeforeOneBlockStartPresences.ElementAt(absentBeforeOneBlockStartPresences.Count() - 1); lastPresence.FlightTime = block.Start - lastPresence.Departure; presences = presences.Concat(new[] { lastPresence }); // Remove the block from worked blocks because worker is absent if (worker.blocksWorked.Contains(block)) { worker.blocksWorked.Remove(block); } } } } return(presences); }
public static void TryUpdateManyToMany <T, TKey>(this DbContext db, IEnumerable <T> currentItems, IEnumerable <T> newItems, Func <T, TKey> getKey) where T : class { db.Set <T>().RemoveRange(currentItems.Except(newItems, getKey)); db.Set <T>().AddRange(newItems.Except(currentItems, getKey)); }
public void SearchIndexTest_GivenSearchSchemasAndModels_EnsureFieldsMatch() { // Arrange IList <string> ErrorLog = new List <string>(); DatasetDefinitionIndex datasetDefinitionIndex = new DatasetDefinitionIndex(); ProvidersIndex providersIndex = new ProvidersIndex(); PublishedFundingIndex publishedfundingindex = new PublishedFundingIndex(); PublishedProviderIndex publishedProviderIndex = new PublishedProviderIndex(); SpecificationIndex specificationindex = new SpecificationIndex(); TemplateIndex templateIndex = new TemplateIndex(); IEnumerable <Type> searchIndexTypes = GetTypesWithSearchIndexAttribute(); IEnumerable <string> indexNames = Directory .GetDirectories(searchIndexDirectoryPath, "*index", SearchOption.TopDirectoryOnly) .Select(m => new DirectoryInfo(m).Name); //Act foreach (string indexName in indexNames) { try { string jsonFilePath = $@"{searchIndexDirectoryPath}\{indexName}\{indexName}.json"; string jsonText = File.ReadAllText(jsonFilePath, Encoding.UTF8); SearchIndexSchema searchIndexSchema = JsonConvert.DeserializeObject <SearchIndexSchema>(jsonText); if (searchIndexSchema?.Name == null) { ErrorLog.Add(string.IsNullOrWhiteSpace(jsonText) ? $"{indexName} json is blank" : $"{indexName} json name is not available"); } else if (searchIndexSchema.Name != indexName) { ErrorLog.Add($"Expected to find index { indexName }, but found { searchIndexSchema.Name }"); } else { Type searchIndexType = searchIndexTypes .FirstOrDefault(m => m.CustomAttributes .FirstOrDefault(p => p.NamedArguments .Any(n => n.TypedValue.Value.ToString() == searchIndexSchema.Name)) != null); IEnumerable <string> searchIndexProperties = searchIndexType.GetProperties() .Select(m => m.CustomAttributes .FirstOrDefault(a => a.AttributeType.Name == "JsonPropertyAttribute") ?.ConstructorArguments[0].Value.ToString().ToLower()) .Where(p => p != null); IEnumerable <string> searchIndexJsonProperties = searchIndexSchema.Fields .Select(m => m.Name.ToLower()) .Where(p => p != null); if (!searchIndexProperties.Any()) { ErrorLog.Add($"Index {indexName}: The model contains no properties"); } else if (!searchIndexJsonProperties.Any()) { ErrorLog.Add($"Index {indexName}: The json contains no properties"); } else { IEnumerable <string> notInJson = searchIndexProperties.Except(searchIndexJsonProperties); if (notInJson.Any()) { string properties = string.Join(",", notInJson); ErrorLog.Add($"Index {indexName}: The model contains the following properties not found in the json schema ({properties})"); } IEnumerable <string> notInModel = searchIndexJsonProperties.Except(searchIndexProperties); if (notInModel.Any()) { string properties = string.Join(",", notInModel); ErrorLog.Add($"Index {indexName}: The json schema contains the following properties not found in the model ({properties})"); } } } } catch (Exception e) { ErrorLog.Add($"Unexpected error checking '{indexName}': {e.Message}{Environment.NewLine}{ e.StackTrace }"); } } //Assert if (ErrorLog.Any()) { Assert.Fail(string.Join(Environment.NewLine, ErrorLog)); } }
public void DrawEffects(IEnumerable <IntVec3> effectRadial) { if (lastRadial == null) { return; } var curCell = effectRadial.Except(lastRadial).RandomElement(); var fadeIn = .2f; var fadeOut = .25f; var solidTime = .05f; if (direction.ToAngleFlat() >= -135 && direction.ToAngleFlat() < -45) { EffectMaker.MakeEffect(WizardryDefOf.Mote_WolfSong_North, curCell.ToVector3(), Map, .8f, angle + Rand.Range(-20, 20), Rand.Range(5, 8), 0, solidTime, fadeOut, fadeIn, true); if (Find.TickManager.TicksGame % 3 == 0) { var effectRadialSmall = GenRadial.RadialCellsAround(ExactPosition.ToIntVec3(), 1, true); curCell = effectRadialSmall.RandomElement(); EffectMaker.MakeEffect(WizardryDefOf.Mote_WolfSong_North, curCell.ToVector3(), Map, .8f, angle + Rand.Range(-20, 20), Rand.Range(10, 15), 0, solidTime, fadeOut, fadeIn, true); } } else if (direction.ToAngleFlat() >= 45 && direction.ToAngleFlat() < 135) { EffectMaker.MakeEffect(WizardryDefOf.Mote_WolfSong_South, curCell.ToVector3(), Map, .8f, angle + Rand.Range(-20, 20), Rand.Range(5, 8), 0, solidTime, fadeOut, fadeIn, true); if (Find.TickManager.TicksGame % 3 == 0) { var effectRadialSmall = GenRadial.RadialCellsAround(ExactPosition.ToIntVec3(), 1, true); curCell = effectRadialSmall.RandomElement(); EffectMaker.MakeEffect(WizardryDefOf.Mote_WolfSong_South, curCell.ToVector3(), Map, .8f, angle + Rand.Range(-20, 20), Rand.Range(10, 15), 0, solidTime, fadeOut, fadeIn, true); } } else if (direction.ToAngleFlat() >= -45 && direction.ToAngleFlat() < 45) { EffectMaker.MakeEffect(WizardryDefOf.Mote_WolfSong_East, curCell.ToVector3(), Map, .8f, angle + Rand.Range(-20, 20), Rand.Range(5, 8), 0, solidTime, fadeOut, fadeIn, true); if (Find.TickManager.TicksGame % 3 == 0) { var effectRadialSmall = GenRadial.RadialCellsAround(ExactPosition.ToIntVec3(), 1, true); curCell = effectRadialSmall.RandomElement(); EffectMaker.MakeEffect(WizardryDefOf.Mote_WolfSong_East, curCell.ToVector3(), Map, .8f, angle + Rand.Range(-20, 20), Rand.Range(10, 15), 0, solidTime, fadeOut, fadeIn, true); } } else { EffectMaker.MakeEffect(WizardryDefOf.Mote_WolfSong_West, curCell.ToVector3(), Map, .8f, angle + Rand.Range(-20, 20), Rand.Range(5, 8), 0, solidTime, fadeOut, fadeIn, true); if (Find.TickManager.TicksGame % 3 == 0) { var effectRadialSmall = GenRadial.RadialCellsAround(ExactPosition.ToIntVec3(), 1, true); curCell = effectRadialSmall.RandomElement(); EffectMaker.MakeEffect(WizardryDefOf.Mote_WolfSong_West, curCell.ToVector3(), Map, .8f, angle + Rand.Range(-20, 20), Rand.Range(10, 15), 0, solidTime, fadeOut, fadeIn, true); } } curCell = lastRadial.RandomElement(); if (!curCell.InBounds(Map) || !curCell.IsValid) { return; } FleckMaker.ThrowSmoke(curCell.ToVector3(), Map, Rand.Range(.4f, .6f)); //var moteSmoke = ThingDef.Named("Mote_Smoke"); //if (Rand.Chance(.5f)) //{ // EffectMaker.MakeEffect(moteSmoke, curCell.ToVector3(), Map, Rand.Range(.8f, 1.3f), // direction.ToAngleFlat(), Rand.Range(.4f, .6f), Rand.Range(-2, 2)); //} //else //{ // EffectMaker.MakeEffect(moteSmoke, curCell.ToVector3(), Map, Rand.Range(.8f, 1.3f), // 180 + direction.ToAngleFlat(), Rand.Range(.4f, .6f), Rand.Range(-2, 2)); //} }
private IEnumerable <CashMatchingDto> CalculateMatchableDocumentDetails(IEnumerable <CashMatchingDto> documentsToMatch, bool isEdit, long?matchFlag) { // get the total avilable amount for each cash. List <CashMatchingDto> matchableDocuments = new List <CashMatchingDto>(); // get all invoices which are not yet used for cash/document matching matchableDocuments.AddRange(documentsToMatch.Where(a => a.MatchFlagId == 0).ToList()); // get the invoices which already used in document matching. List <CashMatchingDto> invoicesWithMatchFlagId = documentsToMatch.Except(matchableDocuments).ToList(); if (invoicesWithMatchFlagId.Count > 0) { // calculate the total amount paid for each invoice List <CashMatchingDto> result = invoicesWithMatchFlagId.GroupBy(d => d.DocumentReference) .Select(g => new CashMatchingDto { DocumentReference = g.Key, AmountToBePaid = g.Sum(s => s.AmountToBePaid), }).ToList(); foreach (var item in result) { var document = invoicesWithMatchFlagId.FirstOrDefault(a => a.DocumentReference == item.DocumentReference); if (document != null) { item.DocumentReference = document.DocumentReference; item.DocumentType = document.DocumentType; item.TransactionDocumentId = document.TransactionDocumentId; item.TransactionDocumentTypeId = document.TransactionDocumentTypeId; item.CurrencyCode = document.CurrencyCode; item.DocumentDate = document.DocumentDate; item.AuthorizedForPosting = document.AuthorizedForPosting; item.CounterPartyId = document.CounterPartyId; item.PaymentTermId = document.PaymentTermId; item.DepartmentId = document.DepartmentId; item.Amount = document.Amount - item.AmountToBePaid; item.ExternalReference = document.ExternalReference; item.Narrative = document.Narrative; item.DepartmentId = document.DepartmentId; item.CharterId = document.CharterId; item.TransactionDirectionID = document.TransactionDirectionID; item.ValueDate = document.ValueDate; item.SecondaryDocumentReference = document.SecondaryDocumentReference; item.AccountLineTypeId = document.AccountLineTypeId; item.InvoiceGLDate = document.InvoiceGLDate; item.SourceCashLineId = document.SourceCashLineId; item.SourceInvoiceId = document.SourceInvoiceId; item.SourceJournalLineId = document.SourceJournalLineId; } } // now update the amount and amounttobepaid for each invoice based in isedit and matchflagid var invoicedDetailsForTheSelectedCash = invoicesWithMatchFlagId.Where(a => a.MatchFlagId == matchFlag).ToList(); foreach (var item in result) { // update each invoice details the cash selected with amount and amounttobepaid CashMatchingDto obj = invoicedDetailsForTheSelectedCash.FirstOrDefault(a => a.DocumentReference == item.DocumentReference); if (obj != null) { // cash is in edit mode , so calculate abvailable total amount n update amountobepaid feild for the invoice belong to this cash if (isEdit) { item.Amount = item.Amount + obj.AmountToBePaid; item.AmountToBePaid = obj.AmountToBePaid; item.IsChecked = true; } else { item.AmountToBePaid = 0; } } else { item.AmountToBePaid = 0; } } return(matchableDocuments.Concat(result.Where(a => a.Amount != 0)).OrderBy(d => d.DocumentReference)); } return(matchableDocuments.OrderBy(d => d.DocumentReference)); }
/// <summary> /// Extension method for Except LINQ extension method that allows us to use lambda /// expression in our LINQ statements instead of custom classes that implement IEqualityComparer. /// </summary> /// <example><![CDATA[ /// List<AuthorInfo> list = GetCurrentAuthorList(); /// List<AuthorInfo> newAuthors = GetNewAuthorList(); /// /// // we don't want duplicates - use Author ID to see if authors are the same /// var uniqueAuthors = newAuthors.Except(list, a=> a.AuthorID); /// AddAuthors(uniqueAuthors); /// ]]></example> public static IEnumerable <T> Except <T, TKey>(this IEnumerable <T> first, IEnumerable <T> second, Func <T, TKey> keyExtractor) { return(first.Except(second, new KeyEqualityComparer <T, TKey>(keyExtractor))); }
private static IEnumerable <IObservable> MergeHydraulicBoundaryLocationCalculations( ObservableList <HydraulicBoundaryLocationCalculationsForTargetProbability> targetCalculations, IEnumerable <HydraulicBoundaryLocationCalculationsForTargetProbability> sourceCalculations, IEnumerable <HydraulicBoundaryLocation> hydraulicBoundaryLocations) { HydraulicBoundaryLocationCalculationsForTargetProbability[] calculationsToMerge = sourceCalculations.Where(stp => targetCalculations .Select(c => c.TargetProbability) .Contains(stp.TargetProbability)) .ToArray(); var changedObjects = new List <IObservable>(); changedObjects.AddRange(MergeCalculations(targetCalculations, calculationsToMerge)); IEnumerable <HydraulicBoundaryLocationCalculationsForTargetProbability> calculationsToAdd = sourceCalculations.Except(calculationsToMerge); if (calculationsToAdd.Any()) { AddCalculations(targetCalculations, calculationsToAdd, hydraulicBoundaryLocations); changedObjects.Add(targetCalculations); } return(changedObjects); }
public void AddDeleteChildren <T, TP, TKey, TIdentity>(IEnumerable <T> itemsToSave, TP parent, Func <T, TKey> getKey, Func <T, TIdentity> getIdentity, Func <TP, IEnumerable <T> > getChild, // Expression<Func<T, bool>> parentFilter, string childRelationName ) where T : class, new() where TP : class, new() { var repository = uow.GetRepository <T>(); var parentRepository = uow.GetRepository <TP>(); //// Type parentType = typeof(TP); Type type = typeof(T); IEnumerable <T> existingItems = null; // check is a identity column exists for the child item. //if so , we have to create it in Mongo DB as well var identityName = repository.GetIdentityName(); int next = 0; //MaxIdentity<TC, TCKey>(Func<TEntity, IEnumerable<TC>> getChild, Func<TC, TCKey> getChildKey) if (!string.IsNullOrEmpty(identityName)) { var maxIdentityInDB = Convert.ToInt64(repository.Get().Max(getIdentity)); var maxIdentityInVersions = Convert.ToInt64(parentRepository.MaxIdentity <T, TIdentity>(getChild, getIdentity)); next = (int)Math.Max(maxIdentityInDB, maxIdentityInVersions) + 1; } //else //{ // //existingItems = repository.GetByID(getParentKey, childRelationName,version); //} //getChild(parent); existingItems = getChild(parent); //(IEnumerable<T>)parentType.GetProperty(childRelationName).GetValue(parent, null); var addedItems = itemsToSave.Except <T, TKey>(existingItems, getKey); var deletedItems = existingItems.Except <T, TKey>(itemsToSave, getKey); //, tchr => tchr.RemoteImageID); var count = addedItems.Count(); if (!string.IsNullOrEmpty(identityName)) { for (int i = 0; i < count; i++) { type.GetProperty(identityName).SetValue(addedItems.ElementAt(i), next, null); next++; } //will not do insert untill approved //repository.Insert(addedItems.ElementAt(i)); } List <T> saveList = existingItems.Union(addedItems).ToList(); count = saveList.Count(); foreach (var deleted in deletedItems) { for (int i = count - 1; i >= 0; i--) { var item = saveList.ElementAt(i); if (getKey(deleted).Equals(getKey(item))) { saveList.RemoveAt(i); } } } // var modifiedItems = images.Except(addedItems, tchr => tchr.RemoteImageID); // add or delete child items , based on availability. //////var count = addedItems.Count(); //////for (int i = 0; i < count; i++) //////{ ////// repository.Insert(addedItems.ElementAt(i)); //////} //var count = deletedItems.Count(); //for (int i = count - 1; i >= 0; i--) //{ // repository.Delete(deletedItems.ElementAt(i)); //} // if the entity is existing and the primary keys (imageID field. not the unique keys accommodationID and RemoteImageID. ) are not sent along with the //foreach (var existing in existingItems) //{ // foreach (var tosave in itemsToSave) // { // if (getKey(existing).Equals(getKey(tosave))) // { // //set the key from existing entry to the new entry // repository.SetKey(existing, tosave); // } // } //} // when updating the children a new version is created . this can be modified to save children to the save version. // may be usefull when both are saved in one click. parentRepository.UpdateChildren <T>(parent, saveList, childRelationName); }
public static IEnumerable <T> Except <T>(this IEnumerable <T> array, T item) { return(array.Except(new T[] { item })); }
IEnumerable <Renderer> MergeRenderers( IEnumerable <Renderer> prev, IEnumerable <Renderer> next) => prev.Except(next, MetadataRendererComparer.Default). Concat(next.Except(prev, MetadataRendererComparer.Default));
/// <summary> /// The get files. /// </summary> /// <param name="path"> /// The path. /// </param> /// <param name="filters"> /// The filters. /// </param> /// <param name="searchOption"> /// The search option. /// </param> /// <param name="directoryAttributesToIgnore"> /// The directory attributes to ignore. /// </param> /// <param name="fileAttributesToIgnore"> /// The file attributes to ignore. /// </param> /// <returns> /// The <see cref="string[]"/>. /// </returns> public static string[] GetFiles( string path, string filters, SearchOption searchOption, FileAttributes directoryAttributesToIgnore, FileAttributes fileAttributesToIgnore) { if (!Directory.Exists(path)) { return(new string[] { }); } var directoryInfo = new DirectoryInfo(path); if (directoryInfo.Parent != null && AnyFlagSet(directoryInfo.Attributes, directoryAttributesToIgnore)) { return(new string[] { }); } IEnumerable <string> include = from filter in filters.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) where !string.IsNullOrEmpty(filter.Trim()) select filter.Trim(); IEnumerable <string> exclude = from filter in include where filter.Contains(@"!") select filter; include = include.Except(exclude); if (!include.Any()) { include = new[] { "*" }; } IEnumerable <string> excludeFilters = from filter in exclude let replace = filter.Replace("!", string.Empty) .Replace(".", @"\.") .Replace("*", ".*") .Replace("?", ".") select string.Format("^{0}$", replace); var excludeRegex = new Regex(string.Join("|", excludeFilters.ToArray()), RegexOptions.IgnoreCase); var pathsToSearch = new Queue <string>(); var foundFiles = new List <string>(); pathsToSearch.Enqueue(path); while (pathsToSearch.Count > 0) { string dir = pathsToSearch.Dequeue(); if (searchOption == SearchOption.AllDirectories) { foreach (string subDir in Directory.GetDirectories(dir) .Where( subDir => (!AnyFlagSet(new DirectoryInfo(subDir).Attributes, directoryAttributesToIgnore)))) { pathsToSearch.Enqueue(subDir); } } foreach (string filter in include) { string[] allfiles = Directory.GetFiles(dir, filter, SearchOption.TopDirectoryOnly); IEnumerable <string> collection = exclude.Any() ? allfiles.Where(p => !excludeRegex.Match(p).Success) : allfiles; foundFiles.AddRange( collection.Where(p => (!AnyFlagSet(new FileInfo(p).Attributes, fileAttributesToIgnore)))); } } return(foundFiles.ToArray()); }
public static void CreateDiffScript(IRepository sourceRepository, IRepository targetRepository, IGenerator generator, bool includeTargetDrops) { List <string> sourceTables = sourceRepository.GetAllTableNames(); List <string> targetTables = targetRepository.GetAllTableNames(); // Script each table not in the target foreach (string tableName in sourceTables.Except(targetTables)) { generator.GenerateTableCreate(tableName); } foreach (string tableName in sourceTables.Except(targetTables)) { generator.GeneratePrimaryKeys(tableName); } foreach (string tableName in sourceTables.Except(targetTables)) { List <string> tableIndexes = sourceRepository.GetIndexesFromTable(tableName).Select(i => i.IndexName).Distinct().ToList(); foreach (var index in tableIndexes) { generator.GenerateIndexScript(tableName, index); } } foreach (string tableName in sourceTables.Except(targetTables)) { generator.GenerateForeignKeys(tableName); } // Drop each table in the target but not the source if (includeTargetDrops) { foreach (string tableName in targetTables.Except(sourceTables)) { generator.GenerateTableDrop(tableName); } } //For each table both in target and source foreach (string tableName in sourceTables.Intersect(targetTables)) { // Check columns for the table: Dropped, added or changed ? IEnumerable <Column> sourceColumns = from c in sourceRepository.GetColumnsFromTable() where c.TableName == tableName select c; IEnumerable <Column> targetColumns = from c in targetRepository.GetColumnsFromTable() where c.TableName == tableName select c; // Added columns foreach (var column in sourceColumns.Except(targetColumns, new ColumnComparer())) { generator.GenerateColumnAddScript(column); } // Same columns, check for changes foreach (var sourceColumn in sourceColumns.Intersect(targetColumns, new ColumnComparer())) { bool altered = false; // Check if they have any differences: var targetColumn = (from c in targetColumns where c.TableName == sourceColumn.TableName && c.ColumnName == sourceColumn.ColumnName select c).Single(); if (sourceColumn.IsNullable != targetColumn.IsNullable) { altered = true; } if (sourceColumn.NumericPrecision != targetColumn.NumericPrecision) { altered = true; } if (sourceColumn.NumericScale != targetColumn.NumericScale) { altered = true; } if (sourceColumn.AutoIncrementBy != targetColumn.AutoIncrementBy) { altered = true; } if (sourceColumn.CharacterMaxLength != targetColumn.CharacterMaxLength) { altered = true; } if (sourceColumn.DataType != targetColumn.DataType) { altered = true; } if (altered) { generator.GenerateColumnAlterScript(sourceColumn); } // Changed defaults is special case if (!targetColumn.ColumnHasDefault && sourceColumn.ColumnHasDefault) { generator.GenerateColumnSetDefaultScript(sourceColumn); } if (!sourceColumn.ColumnHasDefault && targetColumn.ColumnHasDefault) { generator.GenerateColumnDropDefaultScript(sourceColumn); } // If both columns have defaults, but they are different if ((sourceColumn.ColumnHasDefault && targetColumn.ColumnHasDefault) && (sourceColumn.ColumnDefault != targetColumn.ColumnDefault)) { generator.GenerateColumnSetDefaultScript(sourceColumn); } } //Check primary keys List <PrimaryKey> sourcePK = sourceRepository.GetAllPrimaryKeys().Where(p => p.TableName == tableName).ToList(); List <PrimaryKey> targetPK = targetRepository.GetAllPrimaryKeys().Where(p => p.TableName == tableName).ToList(); // Add the PK if (targetPK.Count == 0 && sourcePK.Count > 0) { generator.GeneratePrimaryKeys(tableName); } // Do we have the same columns, if not, drop and create. if (sourcePK.Count > 0 && targetPK.Count > 0) { if (sourcePK.Count == targetPK.Count) { //Compare columns for (int i = 0; i < sourcePK.Count; i++) { if (sourcePK[i].ColumnName != targetPK[i].ColumnName) { generator.GeneratePrimaryKeyDrop(sourcePK[i], tableName); generator.GeneratePrimaryKeys(tableName); break; } } } // Not same column count, just drop and create else { generator.GeneratePrimaryKeyDrop(sourcePK[0], tableName); generator.GeneratePrimaryKeys(tableName); } } // Check indexes List <Index> sourceIXs = sourceRepository.GetIndexesFromTable(tableName); List <Index> targetIXs = targetRepository.GetIndexesFromTable(tableName); // Check added indexes (by name only) foreach (var index in sourceIXs) { var targetIX = targetIXs.Where(s => s.IndexName == index.IndexName); if (targetIX.Count() == 0) { generator.GenerateIndexScript(index.TableName, index.IndexName); } } // Check foreign keys List <Constraint> sourceFKs = sourceRepository.GetAllForeignKeys(tableName); List <Constraint> targetFKs = targetRepository.GetAllForeignKeys(tableName); // Check added foreign keys (by name only) foreach (var fk in sourceFKs) { Constraint targetFK = targetFKs.Where(s => s.ConstraintName == fk.ConstraintName).SingleOrDefault(); if (targetFK == null) { generator.GenerateForeignKey(fk); } } // Check deleted FKs (by name only) foreach (var fk in targetFKs) { Constraint sourceFK = sourceFKs.Where(s => s.ConstraintName == fk.ConstraintName).SingleOrDefault(); if (sourceFK == null) { generator.GenerateForeignKeyDrop(fk); } } // Check deleted indexes (by name only) foreach (var index in targetIXs) { var sourceIX = sourceIXs.Where(s => s.IndexName == index.IndexName); if (sourceIX.Count() == 0) { generator.GenerateIndexOnlyDrop(index.TableName, index.IndexName); } } // Dropped columns foreach (var column in targetColumns.Except(sourceColumns, new ColumnComparer())) { generator.GenerateColumnDropScript(column); } } }
public static IEnumerable <T> SniffOutVoided <T>(this IEnumerable <T> oldStuff, IEnumerable <T> newStuff, IEqualityComparer <T> comparer) { return(oldStuff.Except(newStuff, comparer).ToList()); }
public virtual void InitMediaNavigation(out string mediaNavigationMode, out NavigationData navigationData) { Prepare(); string nextScreenName; AbstractScreenData nextScreen = null; // Try to load the prefered next screen from settings. if (NavigationData.LoadScreenHierarchy(_viewName, out nextScreenName)) { // Support for browsing mode. if (nextScreenName == Consts.USE_BROWSE_MODE) { SetBrowseMode(); } if (_availableScreens != null) { nextScreen = _availableScreens.FirstOrDefault(s => s.GetType().ToString() == nextScreenName); } } IEnumerable <Guid> optionalMIATypeIDs = MediaNavigationModel.GetMediaSkinOptionalMIATypes(MediaNavigationMode); if (_optionalMias != null) { optionalMIATypeIDs = optionalMIATypeIDs.Union(_optionalMias); optionalMIATypeIDs = optionalMIATypeIDs.Except(_necessaryMias); } IFilterTree filterTree = _rootRole.HasValue ? new RelationshipFilterTree(_rootRole.Value) : (IFilterTree) new SimpleFilterTree(); filterTree.AddFilter(_filter); // Prefer custom view specification. ViewSpecification rootViewSpecification = _customRootViewSpecification ?? new MediaLibraryQueryViewSpecification(_viewName, filterTree, _necessaryMias, optionalMIATypeIDs, true) { MaxNumItems = Consts.MAX_NUM_ITEMS_VISIBLE }; if (nextScreen == null) { nextScreen = _defaultScreen; } ScreenConfig nextScreenConfig; NavigationData.LoadLayoutSettings(nextScreen.GetType().ToString(), out nextScreenConfig); Sorting.Sorting nextSortingMode = _availableSortings.FirstOrDefault(sorting => sorting.GetType().ToString() == nextScreenConfig.Sorting) ?? _defaultSorting; Sorting.Sorting nextGroupingMode = _availableGroupings == null || String.IsNullOrEmpty(nextScreenConfig.Grouping) ? null : _availableGroupings.FirstOrDefault(grouping => grouping.GetType().ToString() == nextScreenConfig.Grouping) ?? _defaultGrouping; navigationData = new NavigationData(null, _viewName, MediaNavigationRootState, MediaNavigationRootState, rootViewSpecification, nextScreen, _availableScreens, nextSortingMode, nextGroupingMode) { AvailableSortings = _availableSortings, AvailableGroupings = _availableGroupings, LayoutType = nextScreenConfig.LayoutType, LayoutSize = nextScreenConfig.LayoutSize }; mediaNavigationMode = MediaNavigationMode; }
public static IEnumerable <T> Except <T>(this IEnumerable <T> source, T item) { return(source?.Except(Enumerable.Repeat(item, 1))); }
public static IEnumerable <T> SymmetricDifference <T>(this IEnumerable <T> xs, IEnumerable <T> ys) { // this is probably a shockingly-slow way to do this, but it's concise. return(xs.Except(ys).Concat(ys.Except(xs))); }
private IEnumerable <string> GetTargetLanguages(IEnumerable <string> targetLanguages, TreeNode node) { return(chkSkipTranslated.Checked ? targetLanguages.Except(node.GetTranslatedCultures()) : targetLanguages); }
// TODO: Add tests /// <summary> /// Adds tags to <paramref name="entity"/> based on <paramref name="tags"/>. /// </summary> /// <param name="tags"></param> /// <param name="entity"></param> /// <param name="allTagEntities"></param> public static void SetTags <TEntity, TRelation>(IEnumerable <string> tags, TEntity entity, ICollection <Tag> allTagEntities) where TEntity : IHasTags where TRelation : class, ITagRelation { if (tags.IsNull()) { return; } var nameOfEntity = entity.GetType().Name; var nameOfJoiningProperty = $"{nameOfEntity}{nameof(Tag)}s"; // ie NewsTags var joiningTableType = typeof(Tag).GetProperty(nameOfJoiningProperty).PropertyType.GetGenericArguments()[0]; // ie NewsTag // Get all tag entities that already is created var exisitingTagEntities = allTagEntities? .Where(k => tags.Contains(k.Name, StringComparer.OrdinalIgnoreCase)) ?? new List <Tag>(); // Get a list of all tags that is already attached to the entity to avoid duplicates etc var alreadyAttachedTagEntities = exisitingTagEntities? .Where(k => GetJoiningCollectionInternal <TRelation>(k, nameOfJoiningProperty)? .Any(jt => GetEntityInternal <TEntity>(jt, nameOfEntity).Id == entity.Id) == true ); // Get all joining tables, ie NewsTag, that is already attached var alreadyAttachedJoiningTagEntities = exisitingTagEntities? .SelectMany(k => GetJoiningCollectionInternal <TRelation>(k, nameOfJoiningProperty))? .Where(jt => GetEntityInternal <TEntity>(jt, nameOfEntity).Id == entity.Id) ?? new List <TRelation>(); // Get all existing tags as strings compare them to the param to avoid creating them again var existingTags = exisitingTagEntities? .Select(k => k.Name) ?? new List <string>(); // Finally we have a list of all tags we have to create var newTags = tags?.Except(existingTags); // Create entities var newTagEntities = newTags? .Select(name => new Tag { Name = name, Url = CustomUrlHelper.URLFriendly(name), }); // Get a list of all tag entities that have be attached to the entity var allTagEntitiesToBeAttached = exisitingTagEntities .Except(alreadyAttachedTagEntities) .Concat(newTagEntities ?? new List <Tag>()); // Create new relations between the tag entities and the entity (many-to-many) var joiningTagEntities = allTagEntitiesToBeAttached? .Select(k => Activator.CreateInstance(joiningTableType, k))? // Add all old entities that is already attached (meaning there already exists entities for them) .Concat(alreadyAttachedJoiningTagEntities)? .Select(k => k as TRelation)? .ToList(); // Set the new list of relationship entities to the correct property of the entity entity.GetType().GetProperty(nameOfJoiningProperty).SetValue(entity, joiningTagEntities); }
/// <summary> /// Determine if an array contains all elements in another array /// </summary> /// <typeparam name="T"></typeparam> /// <param name="containingList"></param> /// <param name="lookupList"></param> /// <returns></returns> public static bool ContainsAll <T>(this IEnumerable <T> containingList, IEnumerable <T> lookupList) { return(!lookupList.Except(containingList).Any()); }