ForEach() public static method

public static ForEach ( IEnumerable collection, Action? actionExceptLast = null, Action? actionOnLast = null ) : void
collection IEnumerable
actionExceptLast Action?
actionOnLast Action?
return void
コード例 #1
0
        public void Edit(EditLicenseeData data)
        {
            using (var scope = CustomTransactionScope.GetTransactionScope())
            {
                var validationResult = _licenseeQueries.ValidateCanEdit(data);

                if (!validationResult.IsValid)
                {
                    throw new RegoValidationException(validationResult);
                }

                var licensee = _repository.Licensees
                               .Include(x => x.Products)
                               .Include(x => x.Currencies)
                               .Include(x => x.Countries)
                               .Include(x => x.Cultures)
                               .Include(x => x.Contracts)
                               .Single(x => x.Id == data.Id);

                licensee.Name                = data.Name;
                licensee.CompanyName         = data.CompanyName;
                licensee.AffiliateSystem     = data.AffiliateSystem;
                licensee.ContractStart       = data.ContractStart;
                licensee.ContractEnd         = data.ContractEnd;
                licensee.Email               = data.Email;
                licensee.AllowedBrandCount   = data.BrandCount;
                licensee.AllowedWebsiteCount = data.WebsiteCount;
                licensee.TimezoneId          = data.TimeZoneId;
                licensee.DateUpdated         = DateTimeOffset.UtcNow;
                licensee.UpdatedBy           = _actorInfoProvider.Actor.UserName;
                licensee.Remarks             = data.Remarks;

                var currentContract = licensee.Contracts.Single(x => x.IsCurrentContract);
                currentContract.StartDate = data.ContractStart;
                currentContract.EndDate   = data.ContractEnd;

                licensee.Products.Clear();
                EnumerableExtensions.ForEach(data.Products, x =>
                                             licensee.Products.Add(new LicenseeProduct
                {
                    Licensee  = licensee,
                    ProductId = new Guid(x)
                }));

                licensee.Currencies.Clear();
                EnumerableExtensions.ForEach(data.Currencies, x => licensee.Currencies.Add(_repository.Currencies.Single(y => y.Code == x)));

                licensee.Countries.Clear();
                EnumerableExtensions.ForEach(data.Countries, x => licensee.Countries.Add(_repository.Countries.Single(y => y.Code == x)));

                licensee.Cultures.Clear();
                EnumerableExtensions.ForEach(data.Languages, x => licensee.Cultures.Add(_repository.Cultures.Single(y => y.Code == x)));

                _repository.SaveChanges();

                _eventBus.Publish(new LicenseeUpdated(licensee));

                scope.Complete();
            }
        }
 public void ForEach_argument_null_exception()
 {
     //ARRANGE
     //ACT
     //ASSERT
     Assert.Throws <ArgumentNullException>(() => EnumerableExtensions.ForEach <int>(null, i => { }));
 }
コード例 #3
0
 public static void DeleteDirectoriesWhere(this DirectoryInfo obj, SearchOption searchOption, Func <DirectoryInfo, Boolean> predicate)
 {
     EnumerableExtensions.ForEach(obj.GetDirectories("*.*", searchOption).Where(predicate), (Action <DirectoryInfo>) delegate(DirectoryInfo x)
     {
         x.Delete();
     });
 }
コード例 #4
0
        public IEnumerable <T> FindAssetProviders <T>() where T : class
        {
            if (!this.initialized)
            {
                this.Initialize();
            }
            Queue <AssetProvider> queue = new Queue <AssetProvider>((IEnumerable <AssetProvider>) this.AssetProviders.Values);

            while (queue.Count > 0)
            {
                AssetProvider   provider   = queue.Dequeue();
                AssetAggregator aggregator = provider as AssetAggregator;
                if (aggregator != null)
                {
                    EnumerableExtensions.ForEach <AssetProvider>((IEnumerable <AssetProvider>)aggregator.AssetProviders, (Action <AssetProvider>)(item => queue.Enqueue(item)));
                }
                T result = provider as T;
                if ((object)result != null)
                {
                    if (provider.NeedsUpdate)
                    {
                        provider.Update();
                    }
                    yield return(result);
                }
            }
        }
コード例 #5
0
ファイル: AssetView.cs プロジェクト: radtek/Shopdrawing
 private void IncrementallyChangeList <T>(ObservableCollectionWorkaround <T> oldList, IList <T> newList, IComparer <T> comparer)
 {
     if (newList.Count == 0)
     {
         oldList.Clear();
     }
     else
     {
         IList <T> list;
         if (oldList.Count == 0)
         {
             list = newList;
         }
         else
         {
             HashSet <T> oldItemsSet = new HashSet <T>((IEnumerable <T>)oldList);
             list = (IList <T>)Enumerable.ToList <T>(Enumerable.Where <T>((IEnumerable <T>)newList, (Func <T, bool>)(item => !oldItemsSet.Contains(item))));
             oldItemsSet.ExceptWith((IEnumerable <T>)newList);
             EnumerableExtensions.ForEach <T>((IEnumerable <T>)oldItemsSet, (Action <T>)(item => ((Collection <T>)oldList).Remove(item)));
         }
         foreach (T obj in (IEnumerable <T>)list)
         {
             int index = oldList.BinarySearch(obj, comparer);
             if (index < 0)
             {
                 index = ~index;
             }
             oldList.Insert(index, obj);
         }
     }
 }
コード例 #6
0
        public void ForEach_runs_on_items_that_meet_condition(int expectedCollectionLength, int[] originalCollection)
        {
            var actualCollection = EnumerableExtensions.ForEach(originalCollection,
                                                                item => item * 2, item => item > 1);

            Assert.AreEqual(expectedCollectionLength, actualCollection.Count());
        }
コード例 #7
0
 private static void FindFilesRecursive(DirectoryInfo directory, String pattern, List <FileInfo> foundFiles)
 {
     foundFiles.AddRange(directory.GetFiles(pattern));
     EnumerableExtensions.ForEach((IEnumerable <DirectoryInfo>) directory.GetDirectories(), (Action <DirectoryInfo>) delegate(DirectoryInfo d)
     {
         FindFilesRecursive(d, pattern, foundFiles);
     });
 }
コード例 #8
0
        public void WhenForEachInvoked_ThenCallsActionWithSourceItems()
        {
            string arg = null;

            EnumerableExtensions.ForEach(new[] { "foo" }, s => arg = s);

            Assert.Equal("foo", arg);
        }
コード例 #9
0
 private static void FindFilesRecursive(DirectoryInfo directory, Func <FileInfo, Boolean> predicate, List <FileInfo> foundFiles)
 {
     foundFiles.AddRange(directory.GetFiles().Where(predicate));
     EnumerableExtensions.ForEach((IEnumerable <DirectoryInfo>) directory.GetDirectories(), (Action <DirectoryInfo>) delegate(DirectoryInfo d)
     {
         FindFilesRecursive(d, predicate, foundFiles);
     });
 }
コード例 #10
0
        public void ForEach_NonEmptyEnumerableGiven_ShouldCallMapFunction()
        {
            List <int> actual = new List <int>();

            int[] input = new[] { 1 };
            EnumerableExtensions.ForEach(input, (_) => actual.Add(_));
            Assert.True(actual.Contains(input[0]));
        }
コード例 #11
0
        public void ForEach_CollectionArgumentIsNull_ExpectedException()
        {
            // Arrange
            IEnumerable <string> collection = null;

            // Assert
            Assert.Throws <ArgumentNullException>(() => EnumerableExtensions.ForEach(collection, _ => { }));
        }
コード例 #12
0
        public void ForEach_returns_leaving_original_list_unchanged()
        {
            var myList = new System.Collections.Generic.List <int>(new [] { 1, 2, 3, 5, 6, 7, 8, 9, 10 });

            var newList = EnumerableExtensions.ForEach(myList, item => item * 2);

            CollectionAssert.AreNotEqual(myList, newList);
        }
コード例 #13
0
 private void DocumentService_ActiveDocumentChanged(object sender, DocumentChangedEventArgs e)
 {
     if (e.NewDocument != null && e.NewDocument == this.currentDocument)
     {
         return;
     }
     EnumerableExtensions.ForEach <AssetProvider>((IEnumerable <AssetProvider>) this.AssetProviders, (Action <AssetProvider>)(provider => provider.Assets.Clear()));
     this.Assets.Clear();
     this.NeedsUpdate     = true;
     this.currentDocument = (SceneDocument)null;
 }
コード例 #14
0
 private void RefreshProjectItems()
 {
     AssetLibrary.ResetAssetLoadPerformanceMarker(this.targetProject != null);
     this.ProjectResourceAssetAggregator.ClearProviders();
     if (this.targetProject != null && this.targetProject.Items != null)
     {
         EnumerableExtensions.ForEach <IProjectItem>((IEnumerable <IProjectItem>) this.targetProject.Items, (Action <IProjectItem>)(projectItem => this.TryAddItem(projectItem)));
     }
     this.activeUserThemeProviderCached = false;
     this.InvokeAsync(new Action(this.UpdateAssetsWorker));
     this.NotifyAssetLibraryChanged(AssetLibraryDamages.Categories | AssetLibraryDamages.Assets);
 }
コード例 #15
0
 public async Task AddOrUpdateAsync(
     string profileRolelessId,
     IEnumerable <SubjectAverageRealm> subjectAverages,
     Action <SubjectAverageRealm> action = null)
 {
     if (subjectAverages == null || !subjectAverages.Any <SubjectAverageRealm>())
     {
         return;
     }
     EnumerableExtensions.ForEach <SubjectAverageRealm>((IEnumerable <M0>)subjectAverages, (Action <M0>)(x => x.ProfileId = profileRolelessId));
     await this._subjectAverageRepository.AddOrUpdateAsync(subjectAverages, action);
 }
        public void ForEach_test()
        {
            //ARRANGE
            var agreggate = 0;
            var expected  = 3;
            var source    = new[] { 1, 2 };

            //ACT
            EnumerableExtensions.ForEach(source, i => { agreggate += i; });
            //ASSERT
            Assert.AreEqual(expected, agreggate);
        }
コード例 #17
0
        private void TryChangeWorkingProject()
        {
            IProject project = this.designerContext.ActiveProject;

            if (project == this.workingProject)
            {
                return;
            }
            this.workingProject = project;
            this.UpdateProviders(project);
            EnumerableExtensions.ForEach <UserThemeAssetProvider>(Enumerable.Cast <UserThemeAssetProvider>((IEnumerable)this.AssetProviders), (Action <UserThemeAssetProvider>)(provider => provider.OnProjectChanged(project)));
        }
コード例 #18
0
ファイル: Node.cs プロジェクト: beercsaba/dataobjects-net
        /// <summary>
        /// Removes outgoing connections from node.
        /// </summary>
        /// <param name="destination">Paired node.</param>
        public IEnumerable <NodeConnection <TNodeItem, TConnectionItem> > RemoveConnections(Node <TNodeItem, TConnectionItem> destination)
        {
            ArgumentValidator.EnsureArgumentNotNull(destination, "destination");
            if (outgoingConnections == null)
            {
                return(EnumerableUtils <NodeConnection <TNodeItem, TConnectionItem> > .Empty);
            }

            var nodesToRemove = outgoingConnections.Where(connection => connection.Destination == destination).ToList();

            EnumerableExtensions.ForEach(nodesToRemove, nodeConnection => nodeConnection.UnbindFromNodes());
            return(nodesToRemove);
        }
コード例 #19
0
 public void ForEachByFuncTest(IEnumerable <Int32> value, Type exType, IEnumerable <Int32> result)
 {
     if (exType != null)
     {
         ArgumentException ex =
             (ArgumentException)
             Assert.Throws(exType, () => EnumerableExtensions.ForEach(value, ele => ele * ele));
         Assert.Equal("source", ex.ParamName);
     }
     else
     {
         var tmp = value.ForEach(ele => ele * ele);
         Assert.Equal(result, tmp);
     }
 }
コード例 #20
0
 public void ForEachByActionTest(IEnumerable <Int32> value, Type exType, IEnumerable <Int32> result)
 {
     if (exType != null)
     {
         ArgumentException ex =
             (ArgumentException)
             Assert.Throws(exType, () => EnumerableExtensions.ForEach(value, (ele) => { }));
         Assert.Equal("source", ex.ParamName);
     }
     else
     {
         IList <Int32> tmp = new List <Int32>();
         value.ForEach(ele => tmp.Add(ele * ele));
         Assert.Equal(result, tmp);
     }
 }
コード例 #21
0
ファイル: AssetView.cs プロジェクト: radtek/Shopdrawing
        private void CountAssetCategoriesWorker()
        {
            if (this.Library == null || this.Library.DesignerContext == null || !this.NeedRebuildCategoryCounts)
            {
                return;
            }
            using (PerformanceUtility.PerformanceSequence(PerformanceEvent.AssetViewRecountCategories))
            {
                EnumerableExtensions.ForEach <AssetCategory>(this.AllCategories(), (Action <AssetCategory>)(category => category.AssetCount = 0));
                foreach (Asset asset in this.GetAssetsForCategoryCounting())
                {
                    HashSet <AssetCategoryPath> hashSet = new HashSet <AssetCategoryPath>();
                    using (IEnumerator <AssetCategoryPath> enumerator = asset.Categories.GetEnumerator())
                    {
label_9:
                        while (enumerator.MoveNext())
                        {
                            AssetCategoryPath current = enumerator.Current;
                            hashSet.Add(current);
                            AssetCategoryPath assetCategoryPath = current;
                            while (true)
                            {
                                if (!assetCategoryPath.IsRoot && assetCategoryPath.AlwaysShow)
                                {
                                    hashSet.Add(assetCategoryPath);
                                    assetCategoryPath = assetCategoryPath.Parent;
                                }
                                else
                                {
                                    goto label_9;
                                }
                            }
                        }
                    }
                    foreach (AssetCategoryPath index in hashSet)
                    {
                        AssetCategory assetCategory = this.RootCategory[index];
                        if (assetCategory != null)
                        {
                            ++assetCategory.AssetCount;
                        }
                    }
                }
                EnumerableExtensions.ForEach <AssetCategory>(this.AllCategories(), (Action <AssetCategory>)(category => category.NotifyAssetCountChanged()));
                this.assetLibraryDamages &= ~AssetLibraryDamages.CategoryCounts;
            }
        }
コード例 #22
0
        public void UnlinkAllAttachments(AnnotationSceneNode annotation)
        {
            IEnumerable <SceneElement> attachedElements = annotation.AttachedElements;

            if (!Enumerable.Any <SceneElement>(attachedElements))
            {
                return;
            }
            SceneViewModel viewModel = annotation.ViewModel;

            using (SceneEditTransaction editTransaction = viewModel.CreateEditTransaction(StringTable.UnlinkAnnotationUndoUnit))
            {
                EnumerableExtensions.ForEach <SceneElement>(attachedElements, (Action <SceneElement>)(element => AnnotationUtils.RemoveAnnotationReference(element, annotation)));
                AnnotationManagerSceneNode.SetAnnotationParent(annotation, viewModel.RootNode);
                editTransaction.Commit();
            }
        }
コード例 #23
0
        internal void InvalidateAdorners(AnnotationSceneNode annotation, bool fullRebuild)
        {
            IEnumerable <AnnotationAdornerSet> items = Enumerable.Select(Enumerable.Where(Enumerable.Select(annotation.AttachedElements, element => new
            {
                element    = element,
                adornerSet = this.GetOrCreateAdornerSet(element)
            }), param0 => param0.adornerSet != null), param0 => param0.adornerSet);

            if (fullRebuild)
            {
                EnumerableExtensions.ForEach <AnnotationAdornerSet>(items, (Action <AnnotationAdornerSet>)(adornerSet => adornerSet.InvalidateStructure()));
            }
            else
            {
                EnumerableExtensions.ForEach <AnnotationAdornerSet>(items, (Action <AnnotationAdornerSet>)(adornerSet => adornerSet.InvalidateRender()));
            }
        }
コード例 #24
0
 public void ForEach()
 {
     tlog.Debug(tag, $"ForEach START");
     try
     {
         var list = new List <GestureRecognizer>()
         {
             new GestureRecognizer()
         };
         Action <GestureRecognizer> action = (g) => { };
         EnumerableExtensions.ForEach <GestureRecognizer>(list, action);
     }
     catch (Exception e)
     {
         Assert.Fail("Catch exception: " + e.Message.ToString());
     }
     tlog.Debug(tag, $"ForEach END");
 }
コード例 #25
0
        public static BitmapSource OverlayInk(BitmapSource bitmapSource, double scale, StrokeCollection inkStrokes)
        {
            if (bitmapSource == null)
            {
                return((BitmapSource)null);
            }
            if (inkStrokes == null || inkStrokes.Count == 0)
            {
                return(bitmapSource);
            }
            Rect   rect1        = new Rect(0.0, 0.0, (double)bitmapSource.PixelWidth, (double)bitmapSource.PixelHeight);
            Vector offsetVector = (Vector)RectExtensions.GetCenter(rect1);
            Rect   rect2        = RectExtensions.Union(Enumerable.Select <Stroke, Rect>((IEnumerable <Stroke>)inkStrokes, (Func <Stroke, Rect>)(stroke => stroke.GetBounds())));

            rect2.Scale(scale, scale);
            rect2.Offset(offsetVector);
            Rect   rect3   = Rect.Union(rect1, rect2);
            Canvas canvas1 = new Canvas();

            canvas1.Width  = rect3.Width;
            canvas1.Height = rect3.Height;
            canvas1.Children.Add((UIElement) new Image()
            {
                Source = (ImageSource)bitmapSource
            });
            UIElementCollection children      = canvas1.Children;
            InkPresenter        inkPresenter1 = new InkPresenter();

            inkPresenter1.Strokes         = inkStrokes;
            inkPresenter1.Margin          = new Thickness(offsetVector.X, offsetVector.Y, -offsetVector.X, -offsetVector.Y);
            inkPresenter1.LayoutTransform = (Transform) new ScaleTransform(scale, scale);
            InkPresenter inkPresenter2 = inkPresenter1;

            children.Add((UIElement)inkPresenter2);
            Canvas canvas2   = canvas1;
            Point  newOrigin = new Point(-rect3.Left, -rect3.Top);

            EnumerableExtensions.ForEach <UIElement>(Enumerable.OfType <UIElement>((IEnumerable)canvas2.Children), (Action <UIElement>)(child => DependencyObjectExtensions.SetCanvasPos((DependencyObject)child, newOrigin)));
            return(new FrameworkElementCapturer((FrameworkElement)canvas2, ImageCapturer.MaxSize).Capture());
        }
コード例 #26
0
 private void SceneViewModel_LateSceneUpdatePhase(object sender, SceneUpdatePhaseEventArgs args)
 {
     if (this.sceneViewModel.DesignerContext == null || this.sceneViewModel.DesignerContext.ActiveView == null)
     {
         return;
     }
     if (args.IsRadicalChange || this.referenceSub.CurrentViewModel == null || this.annotationSub.CurrentViewModel == null)
     {
         this.annotationSub.SetSceneRootNodeAsTheBasisNode(this.sceneViewModel);
         this.referenceSub.SetSceneRootNodeAsTheBasisNode(this.sceneViewModel);
     }
     else
     {
         this.annotationSub.Update(this.sceneViewModel, args.DocumentChanges, args.DocumentChangeStamp);
         this.referenceSub.Update(this.sceneViewModel, args.DocumentChanges, args.DocumentChangeStamp);
     }
     if (!args.IsDirtyViewState(SceneViewModel.ViewStateBits.AnnotationSelection) || this.AnnotationLayer == null)
     {
         return;
     }
     EnumerableExtensions.ForEach <AnnotationVisual>(this.AnnotationVisuals, (Action <AnnotationVisual>)(visual => visual.ViewModel.RefreshProperty("Selected")));
 }
コード例 #27
0
        private void UpdateProviders(IProject project)
        {
            IXamlProject    xamlProject    = project as IXamlProject;
            IProjectContext projectContext = xamlProject == null ? (IProjectContext)null : xamlProject.ProjectContext;
            IPlatform       platform       = projectContext == null ? (IPlatform)null : projectContext.Platform;

            if (platform == null)
            {
                return;
            }
            IEnumerable <AssetProvider> items = (IEnumerable <AssetProvider>)platform.Metadata.GetPlatformCache(DesignSurfacePlatformCaches.UserThemeAssetAggregatorProviderCache);

            this.ClearProviders();
            if (items != null)
            {
                EnumerableExtensions.ForEach <AssetProvider>(items, (Action <AssetProvider>)(provider => this.AddProvider(provider)));
            }
            else
            {
                this.CreateProviders(platform);
                platform.Metadata.SetPlatformCache(DesignSurfacePlatformCaches.UserThemeAssetAggregatorProviderCache, (object)Enumerable.ToArray <AssetProvider>((IEnumerable <AssetProvider>) this.AssetProviders));
            }
        }
コード例 #28
0
 public void ForEach_Throws_When_Source_Is_Null()
 {
     // ACT
     Assert.Throws <ArgumentNullException>(() => EnumerableExtensions.ForEach <string>(null, _ => { }));
 }
コード例 #29
0
        public Guid Add(AddLicenseeData data)
        {
            using (var scope = CustomTransactionScope.GetTransactionScope())
            {
                var validationResult = _licenseeQueries.ValidateCanAdd(data);

                if (!validationResult.IsValid)
                {
                    throw new RegoValidationException(validationResult);
                }

                var licensee = new Licensee
                {
                    Id                  = data.Id ?? Guid.NewGuid(),
                    Name                = data.Name,
                    CompanyName         = data.CompanyName,
                    AffiliateSystem     = data.AffiliateSystem,
                    ContractStart       = data.ContractStart,
                    ContractEnd         = data.ContractEnd,
                    Email               = data.Email,
                    AllowedBrandCount   = data.BrandCount,
                    AllowedWebsiteCount = data.WebsiteCount,
                    TimezoneId          = data.TimeZoneId,
                    Status              = LicenseeStatus.Inactive,
                    DateCreated         = DateTimeOffset.UtcNow,
                    CreatedBy           = _actorInfoProvider.Actor.UserName,
                    Contracts           = new List <Contract>
                    {
                        new Contract
                        {
                            Id                = Guid.NewGuid(),
                            StartDate         = data.ContractStart,
                            EndDate           = data.ContractEnd,
                            IsCurrentContract = true
                        }
                    }
                };

                if (data.Products != null)
                {
                    EnumerableExtensions.ForEach(data.Products, x =>
                                                 licensee.Products.Add(new LicenseeProduct
                    {
                        ProductId = new Guid(x)
                    }));
                }

                EnumerableExtensions.ForEach(data.Currencies, x => licensee.Currencies.Add(_repository.Currencies.Single(y => y.Code == x)));
                EnumerableExtensions.ForEach(data.Countries, x => licensee.Countries.Add(_repository.Countries.Single(y => y.Code == x)));
                EnumerableExtensions.ForEach(data.Languages, x => licensee.Cultures.Add(_repository.Cultures.Single(y => y.Code == x)));

                _repository.Licensees.Add(licensee);
                _repository.SaveChanges();

                _eventBus.Publish(new LicenseeCreated
                {
                    Id              = licensee.Id,
                    Name            = licensee.Name,
                    CompanyName     = licensee.CompanyName,
                    Email           = licensee.Email,
                    AffiliateSystem = licensee.AffiliateSystem,
                    ContractStart   = licensee.ContractStart,
                    ContractEnd     = licensee.ContractEnd,
                    Languages       = licensee.Cultures.Select(c => c.Code)
                });

                scope.Complete();

                return(licensee.Id);
            }
        }
コード例 #30
0
        public void ForEachNullTest()
        {
            var count = 0;

            EnumerableExtensions.ForEach <string>(null, x => count++);
        }