C# (CSharp) IEnumerable Code Examples

C# (CSharp) IEnumerable - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для IEnumerable, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
 /// <summary>
 /// Executes this operation
 /// </summary>
 /// <param name="rows">The rows.</param>
 /// <returns></returns>
 public override IEnumerable<Row> Execute(IEnumerable<Row> rows)
 {
     using (IDbConnection connection = Use.Connection(ConnectionStringName))
     using (IDbTransaction transaction = connection.BeginTransaction())
     {
         foreach (Row row in new SingleRowEventRaisingEnumerator(this, rows))
         {
             using (IDbCommand cmd = connection.CreateCommand())
             {
                 currentCommand = cmd;
                 currentCommand.Transaction = transaction;
                 PrepareCommand(currentCommand, row);
                 currentCommand.ExecuteNonQuery();
             }
         }
         if (PipelineExecuter.HasErrors)
         {
             Warn("Rolling back transaction in {0}", Name);
             transaction.Rollback();
             Warn("Rolled back transaction in {0}", Name);
         }
         else
         {
             Debug("Committing {0}", Name);
             transaction.Commit();
             Debug("Committed {0}", Name);
         }
     }
     yield break;
 }
Пример #2
0
        public string Build(BundleType type, IEnumerable<string> files)
        {
            if (files == null || !files.Any())
                return string.Empty;

            string bundleVirtualPath = this.GetBundleVirtualPath(type, files);
            var bundleFor = BundleTable.Bundles.GetBundleFor(bundleVirtualPath);
            if (bundleFor == null)
            {
                lock (s_lock)
                {
                    bundleFor = BundleTable.Bundles.GetBundleFor(bundleVirtualPath);
                    if (bundleFor == null)
                    {
                        var nullOrderer = new NullOrderer();

                        Bundle bundle = (type == BundleType.Script) ?
                            new CustomScriptBundle(bundleVirtualPath) as Bundle :
                            new SmartStyleBundle(bundleVirtualPath) as Bundle;
                        bundle.Orderer = nullOrderer;

                        bundle.Include(files.ToArray());

                        BundleTable.Bundles.Add(bundle);
                    }
                }
            }

            if (type == BundleType.Script)
                return Scripts.Render(bundleVirtualPath).ToString();

            return Styles.Render(bundleVirtualPath).ToString();
        }
Пример #3
0
 public bool Applies(ShoppingCartQuantityProduct quantityProduct, IEnumerable<ShoppingCartQuantityProduct> cartProducts) {
     if (DiscountPart == null) return false;
     var now = _clock.UtcNow;
     if (DiscountPart.StartDate != null && DiscountPart.StartDate > now) return false;
     if (DiscountPart.EndDate != null && DiscountPart.EndDate < now) return false;
     if (DiscountPart.StartQuantity != null &&
         DiscountPart.StartQuantity > quantityProduct.Quantity)
         return false;
     if (DiscountPart.EndQuantity != null &&
         DiscountPart.EndQuantity < quantityProduct.Quantity)
         return false;
     if (!string.IsNullOrWhiteSpace(DiscountPart.Pattern)) {
         string path;
         if (DiscountPart.DisplayUrlResolver != null) {
             path = DiscountPart.DisplayUrlResolver(quantityProduct.Product);
         }
         else {
             var urlHelper = new UrlHelper(_wca.GetContext().HttpContext.Request.RequestContext);
             path = urlHelper.ItemDisplayUrl(quantityProduct.Product);
         }
         if (!path.StartsWith(DiscountPart.Pattern, StringComparison.OrdinalIgnoreCase))
             return false;
     }
     if (DiscountPart.Roles.Any()) {
         var user = _wca.GetContext().CurrentUser;
         if (user.Has<UserRolesPart>()) {
             var roles = user.As<UserRolesPart>().Roles;
             if (!roles.Any(r => DiscountPart.Roles.Contains(r))) return false;
         }
     }
     return true;
 }
 public SetUnmodifiedCommand(string sitePath, IEnumerable<DocumentFile> documents, IEnumerable<StaticFile> files, IEnumerable<LastRunDocument> lastRunState)
 {
     this.Documents = documents;
     this.Files = files;
     this.LastRunState = lastRunState;
     this.SitePath = sitePath;
 }
Пример #5
0
        public IEnumerable<HtmlTag> BuildScriptTags(IEnumerable<string> scripts)
        {
            Func<string, string> toFullUrl = url => _request.ToFullUrl(url);

            while (_queuedScripts.Any())
            {
                var asset = _queuedScripts.Dequeue();
                if (_writtenScripts.Contains(asset)) continue;

                _writtenScripts.Add(asset);

                yield return new ScriptTag(toFullUrl, asset);
            }

            foreach (var x in scripts)
            {
                var asset = _finder.FindAsset(x);

                if (asset == null)
                {
                    yield return new ScriptTag(toFullUrl, null, x);
                }
                else if (!_writtenScripts.Contains(asset))
                {
                    _writtenScripts.Add(asset);
                    yield return new ScriptTag(toFullUrl, asset, x);
                }
            }
        }
Пример #6
0
        internal async Task RemoveAllRenameAnnotationsAsync(IEnumerable<DocumentId> documentWithRenameAnnotations, AnnotationTable<RenameAnnotation> annotationSet, CancellationToken cancellationToken)
        {
            foreach (var documentId in documentWithRenameAnnotations)
            {
                if (_renamedSpansTracker.IsDocumentChanged(documentId))
                {
                    var document = _newSolution.GetDocument(documentId);
                    var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                    // For the computeReplacementToken and computeReplacementNode functions, use 
                    // the "updated" node to maintain any annotation removals from descendants.
                    var newRoot = root.ReplaceSyntax(
                        nodes: annotationSet.GetAnnotatedNodes(root),
                        computeReplacementNode: (original, updated) => annotationSet.WithoutAnnotations(updated, annotationSet.GetAnnotations(updated).ToArray()),
                        tokens: annotationSet.GetAnnotatedTokens(root),
                        computeReplacementToken: (original, updated) => annotationSet.WithoutAnnotations(updated, annotationSet.GetAnnotations(updated).ToArray()),
                        trivia: SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(),
                        computeReplacementTrivia: null);

                    _intermediateSolutionContainingOnlyModifiedDocuments = _intermediateSolutionContainingOnlyModifiedDocuments.WithDocumentSyntaxRoot(documentId, newRoot, PreservationMode.PreserveIdentity);
                }
            }

            _newSolution = _intermediateSolutionContainingOnlyModifiedDocuments;
        }
Пример #7
0
 public static void AddRoleClaims(IEnumerable<string> roles, IList<Claim> claims)
 {
     foreach (string role in roles)
     {
         claims.Add(new Claim(RoleClaimType, role, ClaimsIssuer));
     }
 }
        public Dictionary<string, List<Event>> CreateEvents(string calendarId, IEnumerable<CalendarItem> eventsToCreate)
        {
            var service = _GetCalendarService();
            var eventsToBeCreated = eventsToCreate.Select(eventFromCalendarItem);
            var created = new List<Event>();
            var errored = new List<Event>();

            foreach (var eventToBeCreated in eventsToBeCreated)
            {
                try {
                    Console.WriteLine(string.Format("    -- Creating EVENT [{0}] for dates [{1}]"
                        ,eventToBeCreated.Summary, eventToBeCreated.Start.DateTime.Value));
                    var result = service.Events.Insert(eventToBeCreated, calendarId).Execute();
                    if (result.Id != null && result.Id != "")
                    {
                        created.Add(result);
                    }
                }catch(Exception ex)
                {
                    Console.WriteLine(ex);
                    errored.Add(eventToBeCreated);
                }
            }
            return new Dictionary<string, List<Event>>()
            {
                { "created", created },
                { "errored", errored}
            };
        }
Пример #9
0
        public Dictionary<string, string> Generate(List<NameNode> idNameNodes, IEnumerable<string> excludedNames)
        {
            Generator.Reset();

            int varCount = idNameNodes.Count;
            string[] newNames = new string[varCount];
            var newSubstitution = new Dictionary<string, string>();

            for (int i = 0; i < varCount; i++)
            {
                string newName;
                do
                {
                    newName = Generator.Next();
                }
                while (excludedNames.Contains(newName) || NamesGenerator.CSharpKeywords.Contains(newName));
                newNames[i] = newName;
            }

            int ind = 0;
            foreach (NameNode v in idNameNodes)
                if (!newSubstitution.ContainsKey(v.Name))
                    newSubstitution.Add(v.Name, newNames[ind++]);

            return newSubstitution;
        }
Пример #10
0
        public Announcement(string description, string type, string operatorName, DateTime? startDate, DateTime? endDate, Coordinate location, IEnumerable<string> modes)
        {
            this.OperatorName = operatorName;
            this.Description = description;
            this.StartDate = startDate;
            this.EndDate = endDate;
            this.Location = location;
            this.Type = type;
            this.Modes.AddRange(modes);
            this.RelativeDateString = TimeConverter.ToRelativeDateString(StartDate, true);

            if (modes != null)
            {
                if (modes.Select(x => x.ToLower()).Contains("bus"))
                    this.ModeImages.Add("/Images/64/W/ModeBus.png");
                if (modes.Select(x => x.ToLower()).Contains("rail"))
                    this.ModeImages.Add("/Images/64/W/ModeRail.png");
                if (modes.Select(x => x.ToLower()).Contains("taxi"))
                    this.ModeImages.Add("/Images/64/W/ModeTaxi.png");
                if (modes.Select(x => x.ToLower()).Contains("boat"))
                    this.ModeImages.Add("/Images/64/W/ModeBoat.png");

                if (!this.ModeImages.Any())
                    this.ModeImages.Add("/Images/64/W/ModeBus.png");
            }
            else
            {
                this.Modes.Add("bus");
                this.ModeImages.Add("/Images/64/W/ModeBus.png");
            }
        }
        static IEnumerable<FileRiskFactor> Calculate(IEnumerable<FileModificationStatistics> statistics)
        {
            var riskFactors = new List<FileRiskFactor>();

            foreach (var statistic in statistics)
            {
                var fileRiskFactor = new FileRiskFactor
                {
                    CreatedAt = DateTime.Now,
                    FileName = statistic.FileName,

                    Statistics = statistic
                };

                var existingDuration = GetDaysDuration(statistic.FirstCommit.ModifiedAt, DateTime.Now);
                var localStatistic = statistic;

                foreach (var duration in statistic.OtherCommits.Select(commit => GetDaysDuration(localStatistic.FirstCommit.ModifiedAt, commit.ModifiedAt)))
                {
                    fileRiskFactor.Score += Score(duration, existingDuration);
                }

                riskFactors.Add(fileRiskFactor);
            }

            return riskFactors;
        }
Пример #12
0
 public SupportPowerTimerWidget(World world)
 {
     powers = world.ActorsWithTrait<SupportPowerManager>()
         .Where(p => !p.Actor.IsDead() && !p.Actor.Owner.NonCombatant)
         .SelectMany(s => s.Trait.Powers.Values)
         .Where(p => p.Instances.Any() && p.Info.DisplayTimer && !p.Disabled);
 }
Пример #13
0
 public string GenerateTestFixture(IEnumerable<Test> tests, string fileName)
 {
     var generator = new CodeGenerator(TemplateEnum.MbUnitTestFixture, TestText, MethodText, PropertyText, TypeText,
                                       AssertText);
     var code = generator.GenerateTestFixture(tests.ToList(), fileName);
     return code;
 }
 /// <summary>
 /// Add a decorator to the enumerable for additional processing
 /// </summary>
 /// <param name="operation">The operation.</param>
 /// <param name="enumerator">The enumerator.</param>
 protected override IEnumerable<Row> DecorateEnumerableForExecution(IOperation operation, IEnumerable<Row> enumerator)
 {
     foreach (Row row in new EventRaisingEnumerator(operation, enumerator))
     {
         yield return row;
     }
 }
 public PerformanceCounterInfo(string name, PerformanceCounter performanceCounters, string alias, IEnumerable<ITag> tags)
 {
     _name = name;
     _performanceCounters = performanceCounters;
     _alias = alias;
     _tags = (tags ?? new List<ITag>()).ToList();
 }
        public AppUpdateControl(IEnumerable<IAppVersion> appVersions, Action<IAppVersion> updateAction)
        {
            this.NewestVersion = appVersions.First();
            InitializeComponent();

            this.AppIconImage.ImageFailed += (sender, e) => { this.AppIconImage.Source = new BitmapImage(new Uri("/Assets/windows_phone.png", UriKind.RelativeOrAbsolute)); };
            this.AppIconImage.Source = new BitmapImage(new Uri(HockeyClient.Current.AsInternal().ApiBaseVersion2 + "apps/" + NewestVersion.PublicIdentifier + ".png"));

            this.ReleaseNotesBrowser.Opacity = 0;
            this.ReleaseNotesBrowser.Navigated += (sender, e) => { (this.ReleaseNotesBrowser.Resources["fadeIn"] as Storyboard).Begin(); };
            this.ReleaseNotesBrowser.NavigateToString(WebBrowserHelper.WrapContent(NewestVersion.Notes));
            this.ReleaseNotesBrowser.Navigating += (sender, e) =>
            {
                e.Cancel = true;
                WebBrowserTask browserTask = new WebBrowserTask();
                browserTask.Uri = e.Uri;
                browserTask.Show();
            };
            this.InstallAETX.Click += (sender, e) =>
            {
                WebBrowserTask webBrowserTask = new WebBrowserTask();
                webBrowserTask.Uri = new Uri(HockeyClient.Current.AsInternal().ApiBaseVersion2 + "apps/" + NewestVersion.PublicIdentifier + ".aetx", UriKind.Absolute);
                webBrowserTask.Show();
            };
            this.InstallOverApi.Click += (sender, e) => {
                this.Overlay.Visibility = Visibility.Visible;
                updateAction.Invoke(NewestVersion); 
            };
            
        }
Пример #17
0
 public void Add(IEnumerable<Interaction> set)
 {
     foreach (Interaction interaction in set)
     {
         Add(interaction);
     }
 }
Пример #18
0
 public static Obj_AI_Hero GetTarget(this Spell spell,
     bool ignoreShields = true,
     Vector3 from = default(Vector3),
     IEnumerable<Obj_AI_Hero> ignoredChampions = null)
 {
     return TargetSelector.GetTarget(spell, ignoreShields, from, ignoredChampions);
 }
Пример #19
0
        public Organisation(
            User createdByUser,
            string name,
            string description,
            string website,
            MediaResource avatar,
            MediaResource background,
            IEnumerable<string> categories,
            DateTime createdDateTime,
            Group parentGroup)
            : base(createdByUser,
            name,
            createdDateTime,
            parentGroup)
        {
            Check.RequireNotNull(categories != null, "categories");

            InitMembers();

            SetOrganisationDetails(
                description,
                website,
                avatar,
                background,
                categories);

            ApplyEvent(new DomainModelCreatedEvent<Organisation>(this, createdByUser, this));
        }
 private static Solution UpdateMainDocument(Document document, SyntaxNode root, MethodDeclarationSyntax method, IEnumerable<IGrouping<Document, ReferenceLocation>> documentGroups)
 {
     var mainDocGroup = documentGroups.FirstOrDefault(dg => dg.Key.Equals(document));
     SyntaxNode newRoot;
     if (mainDocGroup == null)
     {
         newRoot = root.ReplaceNode(method, method.AddModifiers(staticToken));
     }
     else
     {
         var diagnosticNodes = mainDocGroup.Select(referenceLocation => root.FindNode(referenceLocation.Location.SourceSpan)).ToList();
         newRoot = root.TrackNodes(diagnosticNodes.Union(new[] { method }));
         newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(method), method.AddModifiers(staticToken));
         foreach (var diagnosticNode in diagnosticNodes)
         {
             var token = newRoot.FindToken(diagnosticNode.GetLocation().SourceSpan.Start);
             var tokenParent = token.Parent;
             if (token.Parent.IsKind(SyntaxKind.IdentifierName)) continue;
             var invocationExpression = newRoot.GetCurrentNode(diagnosticNode).FirstAncestorOrSelfOfType<InvocationExpressionSyntax>()?.Expression;
             if (invocationExpression == null || invocationExpression.IsKind(SyntaxKind.IdentifierName)) continue;
             var memberAccess = invocationExpression as MemberAccessExpressionSyntax;
             if (memberAccess == null) continue;
             var newMemberAccessParent = memberAccess.Parent.ReplaceNode(memberAccess, memberAccess.Name)
                 .WithAdditionalAnnotations(Formatter.Annotation);
             newRoot = newRoot.ReplaceNode(memberAccess.Parent, newMemberAccessParent);
         }
     }
     var newSolution = document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newRoot);
     return newSolution;
 }
 public void AddDoseTimes(IEnumerable<TimeOfDay> times)
 {
     foreach (var time in times)
     {
         AddDoseTime(time);
     }
 }
Пример #22
0
        public override void DoImpact(Target target, Actor firedBy, IEnumerable<int> damageModifiers)
        {
            if (!target.IsValidFor(firedBy))
                return;

            var pos = target.CenterPosition;
            var world = firedBy.World;
            var targetTile = world.Map.CellContaining(pos);
            var isValid = IsValidImpact(pos, firedBy);

            if ((!world.Map.Contains(targetTile)) || (!isValid))
                return;

            var palette = ExplosionPalette;
            if (UsePlayerPalette)
                palette += firedBy.Owner.InternalName;

            var explosion = Explosions.RandomOrDefault(Game.CosmeticRandom);
            if (Image != null && explosion != null)
                world.AddFrameEndTask(w => w.Add(new SpriteEffect(pos, w, Image, explosion, palette)));

            var impactSound = ImpactSounds.RandomOrDefault(Game.CosmeticRandom);
            if (impactSound != null)
                Game.Sound.Play(impactSound, pos);
        }
Пример #23
0
        protected override void OnInitialize()
        {
            base.OnInitialize();

            var pages = new List<SettingsPageViewModel>();
            _settingsEditors = IoC.GetAll<ISettingsEditor>();

            foreach (ISettingsEditor settingsEditor in _settingsEditors)
            {
                List<SettingsPageViewModel> parentCollection = GetParentCollection(settingsEditor, pages);

                SettingsPageViewModel page =
                    parentCollection.FirstOrDefault(m => m.Name == settingsEditor.SettingsPageName);

                if (page == null)
                {
                    page = new SettingsPageViewModel
                    {
                        Name = settingsEditor.SettingsPageName,
                    };
                    parentCollection.Add(page);
                }

                page.Editors.Add(settingsEditor);
            }

            Pages = pages;
            SelectedPage = GetFirstLeafPageRecursive(pages);
        }
 private static void ApplyMetadataAwareAttributes(IEnumerable<Attribute> attributes, ModelMetadata result)
 {
     foreach (IMetadataAware awareAttribute in attributes.OfType<IMetadataAware>())
     {
         awareAttribute.OnMetadataCreated(result);
     }
 }
        /////////////////////////////////////////////////////////////////////////////
        public static void AddFilesToProject( InputFile srcFile, IEnumerable<string> resultFiles, IExtSvcProvider service )
        {
            // ******
            var allPossibleFiles = GetPossibleFileNames( srcFile, resultFiles );
            var filesThatExist = DiscoverGeneratedFiles( srcFile, resultFiles );
            var filesThatDontExist = allPossibleFiles.Except( filesThatExist );

            // ******
            service.AddFilesToProject( filesThatExist );
            service.RemoveFilesFromProject( filesThatDontExist );

            //// ******
            //var sb = new StringBuilder { };
            //
            //sb.Append( "Files that are in, or have just been added to project:\r\n" );
            //foreach( var name in filesThatExist ) {
            //	sb.AppendFormat( "  {0}\r\n", name );
            //}
            //
            //sb.Append( "Files that have been removed from the project:\r\n" );
            //foreach( var name in filesThatDontExist ) {
            //	sb.AppendFormat( "  {0}\r\n", name );
            //}
            //
            //// ******
            //return sb.ToString();
        }
Пример #26
0
        public VertexArray(IOpenGL30 gl, IEnumerable<IVertexBuffer> buffers, IEnumerable<IVertexDescriptor> descriptors)
        {
            IVertexBuffer[] bufferObjects = buffers.ToArray();
            IVertexDescriptor[] descs = descriptors.ToArray();
            if (descs.Length != bufferObjects.Length)
                throw new InvalidOperationException("Number of buffers and number of descriptors must match.");

            
            uint[] handles = new uint[1];
            gl.GenVertexArrays(1, handles);
            if(handles[0] == 0u)
                throw new NoHandleCreatedException();

            _gl = gl;
            Handle = handles.Single();
            Buffers = bufferObjects;
            using (Bind())
            {
                int count = 0;
                for (int index = 0; index < bufferObjects.Length; index++)
                {
                    var buffer = bufferObjects[index];
                    var desc = descs[index];
                    buffer.Bind();
                    Apply(desc, count);
                    count += desc.Elements.Count();
                }
            }
        }
Пример #27
0
 /// <summary>
 /// 添加参数列表
 /// </summary>
 private void AddParams( IEnumerable<KeyValuePair<string, object>> paramList ) {
     foreach ( var parameter in paramList ) {
         if ( IsSecret( parameter.Key ) )
             continue;
         AddParams( parameter );
     }
 }
 public void HttpMethodProviderAttributes_ReturnsCorrectHttpMethodSequence(
     IActionHttpMethodProvider httpMethodProvider,
     IEnumerable<string> expectedHttpMethods)
 {
     // Act & Assert
     Assert.Equal(expectedHttpMethods, httpMethodProvider.HttpMethods);
 }
        protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters)
        {
            yield return new CommandFilter("[property_type]=1");

            yield return new CommandFilter(string.Format("[cube_name]='{0}'"
                                                           , filters.Single(f => f.Target == Target.Perspectives).Caption
                                                           ));

            yield return new CommandFilter(string.Format("[dimension_unique_name]='[{0}]'"
                                                            , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                            ));

            yield return new CommandFilter(string.Format("[hierarchy_unique_name]='[{0}].[{1}]'"
                                                , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                , filters.Single(f => f.Target == Target.Hierarchies).Caption
                                                ));

            yield return new CommandFilter(string.Format("[level_unique_name]='[{0}].[{1}].[{2}]'"
                                                , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                , filters.Single(f => f.Target == Target.Hierarchies).Caption
                                                , filters.Single(f => f.Target == Target.Levels).Caption
                                                ));

            var filter = filters.SingleOrDefault(f => f.Target == Target.Properties);
            if (filter!=null)
                yield return new CommandFilter(string.Format("[property_caption]='{0}'"
                                                           , filter.Caption
                                                           ));
        }
 /// <summary>
 /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
 /// </summary>
 /// <param name="mediaType">The media type.</param>
 /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
 /// <param name="controllerName">Name of the controller.</param>
 /// <param name="actionName">Name of the action.</param>
 /// <param name="parameterNames">The parameter names.</param>
 public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
 {
     if (mediaType == null)
     {
         throw new ArgumentNullException("mediaType");
     }
     if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
     {
         throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
     }
     if (controllerName == null)
     {
         throw new ArgumentNullException("controllerName");
     }
     if (actionName == null)
     {
         throw new ArgumentNullException("actionName");
     }
     if (parameterNames == null)
     {
         throw new ArgumentNullException("parameterNames");
     }
     ControllerName = controllerName;
     ActionName = actionName;
     MediaType = mediaType;
     ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
     SampleDirection = sampleDirection;
 }