当前位置: 首页>>代码示例>>C#>>正文


C# Stack.Any方法代码示例

本文整理汇总了C#中System.Collections.Stack.Any方法的典型用法代码示例。如果您正苦于以下问题:C# Stack.Any方法的具体用法?C# Stack.Any怎么用?C# Stack.Any使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Collections.Stack的用法示例。


在下文中一共展示了Stack.Any方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Parse

        public static IEnumerable<Token> Parse(string code)
        {
            IList<Token> top = new List<Token>();
            Stack<IList<Token>> stack = new Stack<IList<Token>>();

            int pos = 0;

            foreach (char character in code)
            {
                switch (character)
                {
                    case '[':
                        stack.Push(top);
                        top = new List<Token>();
                        break;
                    case ']':
                        if (!stack.Any())
                        {
                            throw new ParseException("Unexpected ] at position " + pos);
                        }
                        IEnumerable<Token> innerTokens = top;
                        top = stack.Pop();
                        top.Add(new Loop(innerTokens));
                        break;
                    case '+':
                        top.Add(new Incr());
                        break;
                    case '-':
                        top.Add(new Decr());
                        break;
                    case '.':
                        top.Add(new Out());
                        break;
                    case ',':
                        top.Add(new In());
                        break;
                    case '<':
                        top.Add(new DecrPtr());
                        break;
                    case '>':
                        top.Add(new IncrPtr());
                        break;
                }

                pos++;
            }

            if (stack.Any())
            {
                throw new ParseException("Expected ] at EOF");
            }

            return top;
        }
开发者ID:paf31,项目名称:BF,代码行数:54,代码来源:BFParser.cs

示例2: Descendants

        /// <summary>
        /// Возвращает всех потомков в дереве.
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public static IEnumerable<IWixElement> Descendants(this IEnumerable<IWixElement> items)
        {
            Stack<IWixElement> stack = new Stack<IWixElement>(items);
              while (stack.Any())
              {
            IWixElement item = stack.Pop();
            yield return item;

            foreach (IWixElement i in item.Items)
              stack.Push(i);
              }
        }
开发者ID:DarkGraf,项目名称:STInstaller,代码行数:17,代码来源:WixElementsExtension.cs

示例3: GetParent

        /// <summary>
        /// Ищет родителя переданного элемента начиная с корневого элемента главной сущности.
        /// Если элемент не найден, вернется null.
        /// </summary>
        /// <param name="mainItem"></param>
        /// <param name="child"></param>
        /// <returns></returns>
        public static IWixElement GetParent(this IWixMainEntity mainItem, IWixElement child)
        {
            Stack<IWixElement> stack = new Stack<IWixElement>();
              stack.Push(mainItem.RootElement);
              while (stack.Any())
              {
            IWixElement item = stack.Pop();

            // Если элемент найден, сразу выходим.
            if (item.Items.Contains(child))
              return item;

            foreach (IWixElement i in item.Items)
              stack.Push(i);
              }

              return null;
        }
开发者ID:DarkGraf,项目名称:STInstaller,代码行数:25,代码来源:WixElementsExtension.cs

示例4: Apply

		protected override object Apply( object value )
		{
			var index = collection.Cast<object>().WithFirst( o => o == null, o =>
			{
				var i = collection.IndexOf( o );
				collection.RemoveAt( i );
				return i;
			}, () => -1 );

			var itemType = collection.GetType().Adapt().GetInnerType();
			var items = new Stack<object>( itemType.IsInstanceOfType( value ) ? value.ToItem() : value.GetType().Adapt().GetInnerType().With( itemType.IsAssignableFrom ) ? value.To<IEnumerable>().Cast<object>() : Items<object>.Default );

			var result = index == -1 && items.Any() ? items.Pop() : null;

			var insert = Math.Max( 0, index );

			foreach ( var item in items )
			{
				collection.Insert( insert, item );
			}
			return result;
		}
开发者ID:DevelopersWin,项目名称:VoteReporter,代码行数:22,代码来源:CollectionMarkupProperty.cs

示例5: IsMatch

        internal static bool IsMatch(this HtmlAgilityPack.HtmlNode node, SimpleSelector selector, Stack<SimpleSelector> remainingStack)
        {
            if (!string.IsNullOrEmpty(selector.ElementName) && node.Name != selector.ElementName)
                return false;

            if (!string.IsNullOrEmpty(selector.ID) && node.Id != selector.ID)
                return false;

            if (!string.IsNullOrEmpty(selector.Class))
            {
                var classString = node.Attributes.Contains("class") ? node.Attributes["class"].Value : "";
                if (!classString.Split(' ').Contains(selector.Class))
                    return false;
            }
            if (!string.IsNullOrEmpty(selector.Pseudo)) {
                if (!node.IsPseudoMatch(selector, remainingStack))
                    return false;
            }

            if (selector.Combinator != null && remainingStack.Any())
            {
                var nextSel = remainingStack.Pop();

                switch (selector.Combinator.Value)
                {
                    case Combinator.ChildOf:

                        if (node.ParentNode == null)//has to be a child of something
                            return false;
                        if(!node.ParentNode.IsMatch(nextSel, remainingStack))
                            return false;
                        break;

                    case Combinator.Namespace:
                        //we are not going to support this until I see a valid use case
                        return false;
                    case Combinator.PrecededBy:

                        if(!node.PreviousSiblingsNotText().Any(x=>x.IsMatch(nextSel, remainingStack)))
                            return false;

                        break;
                    case Combinator.PrecededImmediatelyBy:
                        var sib = node.PreviousSiblingNotText();
                        if (sib == null)//has to be a child of something
                            return false;
                        if (!sib.IsMatch(nextSel, remainingStack))
                            return false;

                        break;
                    default:
                        break;
                }
            }
            if (selector.Attribute != null)
            {
                if (!node.IsMatch(selector.Attribute))
                    return false;
            }
            if (selector.Child != null)
            {
                return node.IsMatch(selector.Child, remainingStack);
            }

            return true;
        }
开发者ID:tocsoft,项目名称:CssInliner,代码行数:66,代码来源:Inliner.cs

示例6: GetEmbeddedDirectory

 private EmbeddedResourceVirtualDirectory GetEmbeddedDirectory(Stack<string> tokens)
 {
     tokens = new Stack<string>(tokens);
     if(!tokens.Any())
     {
         return (EmbeddedResourceVirtualDirectory)RootDirectory;
     }
     var name = tokens.Pop();
     return new EmbeddedResourceVirtualDirectory(this, GetEmbeddedDirectory(tokens), name);
 }
开发者ID:RainsSoft,项目名称:VirtualPath,代码行数:10,代码来源:EmbeddedResourceVirtualPathProvider.cs

示例7: ParseTemplate

        /**
        * Breaks up the given `template` string into a tree of tokens. If the `tags`
        * argument is given here it must be an array with two string values: the
        * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
        * course, the default is to use mustaches (i.e. mustache.tags).
        *
        * A token is an array with at least 4 elements. The first element is the
        * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
        * did not contain a symbol (i.e. {{myValue}}) this element is "Name". For
        * all text that appears outside a symbol this element is "text".
        *
        * The second element of a token is its "Value". For mustache tags this is
        * whatever else was inside the tag besides the opening symbol. For text tokens
        * this is the text itself.
        *
        * The third and fourth elements of the token are the Start and End indices,
        * respectively, of the token in the original template.
        *
        * Tokens that are the root node of a subtree contain two more elements: 1) an
        * array of tokens in the subtree and 2) the index in the original template at
        * which the closing tag for that section begins.
        */
        private static List<Token> ParseTemplate(string template, Tags tags = null)
        {
            if (!template.Any())
                return new List<Token>();

            var sections = new Stack<Token>(); // Stack to hold section tokens
            var tokens = new List<Token>(); // Buffer to hold the tokens
            var spaces = new Stack<int>(); // Indices of whitespace tokens on the current line
            var hasTag = false; // Is there a {{tag}} on the current line?
            var nonSpace = false; // Is there a non-space char on the current line?

            // Strips all whitespace tokens array for the current line
            // if there was a {{#tag}} on it and otherwise only space.
            Action stripSpace = () =>
            {
                if (hasTag && !nonSpace)
                {
                    while (spaces.Any())
                        tokens.RemoveAt(spaces.Pop());
                }
                else
                {
                    spaces.Clear();
                }

                hasTag = false;
                nonSpace = false;
            };

            // TODO: this `= null` is to avoid "Use of unassigned local variable" C# compiler error.
            Regex openingTagRe = null;
            Regex closingTagRe = null;
            Regex closingCurlyRe = null;
            Action<Tags> compileTags = delegate(Tags tagsToCompile)
            {
                openingTagRe = new Regex(Regex.Escape(tagsToCompile.Opener) + "\\s*");
                closingTagRe = new Regex("\\s*" + Regex.Escape(tagsToCompile.Closer));
                closingCurlyRe = new Regex("\\s*" + Regex.Escape('}' + tagsToCompile.Closer));
            };

            if (tags == null)
                compileTags(MustacheTags);
            else
                compileTags(tags);

            //var Start, Type, Value, chr, token, openSection;
            var scanner = new Scanner(template);
            Token openSection = null;
            while (!scanner.Eos())
            {
                var start = scanner._pos;
                var value = scanner.ScanUntil(openingTagRe);
                var valueLength = value.Length;
                if (valueLength > 0)
                {
                    for (var i = 0; i < valueLength; ++i)
                    {
                        string chr = "" + value[i];

                        if (IsWhitespace(chr))
                        {
                            spaces.Push(tokens.Count);
                        }
                        else
                        {
                            nonSpace = true;
                        }

                        tokens.Add(new Token {Type = "text", Value = chr, Start = start, End = start + 1});
                        start += 1;

                        // Check for whitespace on the current line.
                        if (chr == "\n")
                            stripSpace();
                    }
                }

                // Match the opening tag.
//.........这里部分代码省略.........
开发者ID:vahpetr,项目名称:MustacheCs2,代码行数:101,代码来源:Mustache.cs

示例8: NestTokens

        /**
        * Forms the given array of `tokens` into a nested tree structure where
        * tokens that represent a section have two additional items: 1) an array of
        * all tokens that appear in that section and 2) the index in the original
        * template that represents the End of that section.
        */
        public static List<Token> NestTokens(List<Token> tokens)
        {
            var nestedTokens = new List<Token>();
            var collector = nestedTokens;
            var sections = new Stack<Token>();

            var l = tokens.Count;
            for (var i = 0; i < l; ++i)
            {
                var token = tokens[i];

                switch (token.Type)
                {
                    case "#":
                    case "^":
                        collector.Add(token);
                        sections.Push(token);
                        token.SubTokens = new List<Token>();
                        collector = token.SubTokens;
                        break;
                    case "/":
                        var section = sections.Pop();
                        section.EndSection = token.Start;
                        if (sections.Any())
                            collector = sections.Peek().SubTokens;
                        else
                            collector = nestedTokens;
                        break;
                    default:
                        collector.Add(token);
                        break;
                }
            }

            return nestedTokens;
        }
开发者ID:vahpetr,项目名称:MustacheCs2,代码行数:42,代码来源:Mustache.cs

示例9: CompileTokenFile

        protected async Task CompileTokenFile(CancellationToken cancellationToken) {
            try {
                await TaskEx.Run(() => {
                    _languageRoot = new CodeTypeDeclarationRoot() { Project = _document.Project };
                    CodeTypeDeclarationEx initialparent = _languageRoot;


                    cancellationToken.ThrowIfCancellationRequested();

                    _dependingOnSave = this.DependingOn;

                    #region Clean Up

                    _document.Project.Solution.ErrorService.ClearAllErrorsFrom(_document, Errors.ErrorSource.ASTParser);
                    _codeRangeManager.Clear();

                    #endregion

                    #region Merge DependingOn Members

                    if(_dependingOnSave == null) {
                        // merge super base members
                        _languageRoot.Members.AddRange(_root.Members);
                        firstAfterNull = true;
                    } else {

                        //if(!_project.IsInUpdate) {
                        //    if(firstAfterNull) {
                        //        ignoreDependingOnce = true;
                        //        _dependingOnSave.CompileTokenFileAsync();
                        //        firstAfterNull = false;
                        //    }
                        //    _dependingOnSave.WaitUntilUpdated(200);
                        //}
                        
                        _languageRoot.Members.AddRange(_dependingOnSave.GetRootTypeSnapshot().Members);
                    }

                    #endregion

                    var codeLineMap = _document.SegmentService.GetCodeSegmentLinesMap();
                    CodeTypeDeclaration parent = initialparent;
                    Stack<CodeSegment> paramstack = new Stack<CodeSegment>();
                    int linecnt = 0;
                    if(codeLineMap.Keys.Any())
                        linecnt = codeLineMap.Keys.Max();

                    CodeTokenLine line;

                    Stack<CodeTypeDeclarationEx> parentHirarchy = new Stack<CodeTypeDeclarationEx>();
                    int bcc = 0;
                    parentHirarchy.Push(initialparent);

                    cancellationToken.ThrowIfCancellationRequested();

                    #region Parse

                    for(int i = 0; i <= linecnt; i++) {

                        cancellationToken.ThrowIfCancellationRequested();

                        if(codeLineMap.ContainsKey(i))
                            line = codeLineMap[i];
                        else
                            continue;

                        // is class definition?:

                        #region Parse Class Definition

                        var classkeywordSegment = line.CodeSegments[0].ThisOrNextOmit(whitespacetokenNewLines);
                        if(classkeywordSegment != null && classkeywordSegment.Token == Token.KeyWord && classkeywordSegment.TokenString.Equals("class", StringComparison.CurrentCultureIgnoreCase)) {
                            var classNameSegment = classkeywordSegment.FindNextOnSameLine(Token.Identifier);
                            if(classNameSegment != null) {

                                var next = classNameSegment.NextOmit(whitespacetokenNewLines);
                                if(next != null) {
                                    CodeTypeDeclarationEx thisparent = parentHirarchy.Any() ? parentHirarchy.Peek() : _languageRoot;
                                    CodeTypeReferenceEx basecls = null;
                                    CodeSegment refBaseClass = null;
                                    if(next.Token == Token.KeyWord && next.TokenString.Equals("extends", StringComparison.InvariantCultureIgnoreCase)) {
                                        refBaseClass = next.NextOmit(whitespacetokenNewLines);

                                        if(refBaseClass != null) {
                                            if(refBaseClass.Token == Token.Identifier) {
                                                refBaseClass.CodeDOMObject = basecls = new CodeTypeReferenceEx(_document, refBaseClass.TokenString, thisparent);
                                                next = refBaseClass.NextOmit(whitespacetokenNewLines);
                                            } else {
                                                RegisterError(_document, next.Next, "Expected: Class Name Identifier");
                                                next = next.NextOmit(whitespacetokenNewLines);
                                            }
                                        } else {
                                            if(next.Next != null && next.Next.Token != Token.BlockOpen) {
                                                RegisterError(_document, next.Next, "Expected: Class Name Identifier");
                                                next = next.NextOmit(whitespacetokenNewLines);
                                            }
                                        }
                                    }

                                    if(next != null) {
//.........这里部分代码省略.........
开发者ID:RaptorOne,项目名称:SmartDevelop,代码行数:101,代码来源:CodeDOMDocumentServiceAHK.cs

示例10: FindGridletPath

 public NavigationGridlet[] FindGridletPath(NavigationGridlet start, NavigationGridlet end)
 {
     Dictionary<NavigationGridlet, int> scoresByGridlet = new Dictionary<NavigationGridlet, int>();
      scoresByGridlet.Add(start, 0);
      var s = new Stack<KeyValuePair<NavigationGridlet, int>>();
      s.Push(new KeyValuePair<NavigationGridlet, int>(start, 0));
      bool success = false;
      while (s.Any()) {
     var kvp = s.Pop();
     foreach (var neighbor in kvp.Key.Neighbors) {
        if (!scoresByGridlet.ContainsKey(neighbor) && neighbor.IsEnabled) {
           scoresByGridlet.Add(neighbor, kvp.Value + 1);
           s.Push(new KeyValuePair<NavigationGridlet, int>(neighbor, kvp.Value + 1));
           if (neighbor == end) {
              success = true;
              break;
           }
        }
     }
      }
      if (!success) {
     Console.WriteLine("GRidlet pathing failed!");
     return null;
      } else {
     var current = end;
     List<NavigationGridlet> path = new List<NavigationGridlet>();
     while (current != start) {
        path.Add(current);
        int minimumDistance = Int32.MaxValue;
        NavigationGridlet minimumNeighbor = null;
        foreach (var neighbor in current.Neighbors) {
           int score;
           if (scoresByGridlet.TryGetValue(neighbor, out score)) {
              if (minimumDistance > score) {
                 minimumDistance = score;
                 minimumNeighbor = neighbor;
              }
           }
        }
        current = minimumNeighbor;
     }
     path.Add(start);
     var result = path.ToArray();
     Array.Reverse(result);
     return result;
      }
 }
开发者ID:ItzWarty,项目名称:AdventuresInShade,代码行数:47,代码来源:Pathfinder.cs

示例11: GetBestPathFrom

        private static Path GetBestPathFrom(Board b, Options o, int y, int x)
        {
            Path bestPath = new Path();
            Stack<Tuple<Board, Path>> paths = new Stack<Tuple<Board, Path>>();
            paths.Push(new Tuple<Board, Path>(b, new Path
            {
                Start = new Tuple<int, int>(y, x),
                Current = new Tuple<int, int>(y, x),
                Depth = 1,
                Score = b.Score(BoardScorer.Options.Horus)
            }));
            while (paths.Any())
            {
                var cur = paths.Pop();
                var curPath = cur.Item2;
                var curBoard = cur.Item1;
                if (curPath.Score > bestPath.Score)
                    bestPath = curPath;
                if (curPath.Depth == o.MaxDepth)
                    continue;
                //if (paths.Count() > o.WhenToPrune)
                //{
                //    var newPaths = new Stack<Tuple<Board, Path>>();
                //    foreach (var path in paths.OrderByDescending(p => p.Item2.Score).Take(o.NumToKeep).Reverse())
                //        newPaths.Push(path);
                //    paths = newPaths;
                //}

                foreach (var direction in Board.MoveDirections)
                {
                    if (curPath.Length != 0 &&
                        curPath.Actions.Last()[0] == -direction[0] &&
                        curPath.Actions.Last()[1] == -direction[1])
                        continue;
                    var newY = curPath.Current.Item1 + direction[0];
                    var newX = curPath.Current.Item2 + direction[1];
                    if (newY < 0 || newY >= b.Height ||
                        newX < 0 || newX >= b.Width)
                        continue;
                    Board newBoard = new Board(curBoard);
                    Orb tempOrb = newBoard.Orbs[newY, newX];
                    newBoard.Orbs[newY, newX] = newBoard.Orbs[curPath.Current.Item1, curPath.Current.Item2];
                    newBoard.Orbs[curPath.Current.Item1, curPath.Current.Item2] = tempOrb;
                    var newPath = new List<int[]>(curPath.Actions);
                    newPath.Add(direction);
                    paths.Push(new Tuple<Board, Path>(newBoard, new Path
                    {
                        Start = curPath.Start,
                        Current = new Tuple<int, int>(newY, newX),
                        Depth = curPath.Depth + 1,
                        Score = newBoard.Score(BoardScorer.Options.Horus) - curPath.Depth / 100,
                        Actions = newPath
                    }));
                }
            }
            return bestPath;
        }
开发者ID:toraora,项目名称:PadPlayer,代码行数:57,代码来源:DfsSolver.cs

示例12: Local

        private static List<MondaiWord> 正解探索(CorrectAnswer rightAnswer, List<MondaiWord> a)
        {
            int i = 0;
            var b = new List<MondaiWord>();
            var stack = new Stack<Local>();
            stack.Push(new Local(i, a, b));
            while (stack.Any())
            {
                var temp = stack.Pop();
                i = temp._i;
                a = temp._a;
                b = temp._b;

                while (i < a.Count())
                {
                    var bb = new List<MondaiWord>(b.Count() + 1);
                    bb.AddRange(b);
                    bb.Add(a[i]);
                    if (!rightAnswer.StartsWith(bb))
                    {
                        i++;
                        continue;
                    }
                    if (rightAnswer.IsMatch(bb))
                    {
                        return bb;
                    }
                    var aa = new List<MondaiWord>(a);
                    aa.RemoveAt(i);

                    stack.Push(new Local(i + 1, a, b));
                    i = 0;
                    a = aa;
                    b = bb;
                }
            }
            return null;

            /*			for (int i = 0; i < a.Count(); i++)
            {
                if (!b.Any() && !a[i].HasLeftJoint && !rightAnswer.Text.StartsWith(a[i].Text, StringComparison.Ordinal))
                {
                    continue;
                }

                var aa = new List<MondaiWord>(a);
                aa.RemoveAt(i);

                var bb = new List<MondaiWord>(b);
                bb.Add(a[i]);

                if (!rightAnswer.StartsWith(bb))
                {
                    continue;
                }
                if (rightAnswer.IsMatch(bb))
                {
                    return bb;
                }

                var result = 正解探索(rightAnswer, aa, bb);
                if (null != result) return result;
            }
            return null;*/
        }
开发者ID:kaijin-games,项目名称:larning-english-game,代码行数:65,代码来源:Shomon.cs


注:本文中的System.Collections.Stack.Any方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。