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


C# Stack.Select方法代码示例

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


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

示例1: GetValue

 public IItem GetValue(IDictionary<string, IItem> variables) {
   var stack = new Stack<object>();
   int i = 0;
   try {
     for (; i < tokens.Count; i++) {
       var token = tokens[i];
       double d;
       if (TryParse(token, out d)) {
         stack.Push(d);
       } else if (token.StartsWith("\"")) {
         stack.Push(GetVariableValue(variables, token.Substring(1, token.Length - 2).Replace("\\\"", "\"")));
       } else if (token.StartsWith("'")) {
         stack.Push(token.Substring(1, token.Length - 2).Replace("\\'", "'"));
       } else {
         Apply(token, stack, variables);
       }
     }
   } catch (Exception x) {
     throw new Exception(string.Format(
       "Calculation of '{1}'{0}failed at token #{2}: {3} {0}current stack is: {0}{4}", Environment.NewLine,
       Formula, i, TokenWithContext(tokens, i, 3),
       string.Join(Environment.NewLine, stack.Select(AsString))),
       x);
   }
   if (stack.Count != 1)
     throw new Exception(
       string.Format("Invalid final evaluation stack size {0} (should be 1) in formula '{1}'",
       stack.Count, Formula));
   var result = stack.Pop();
   if (result is string) return new StringValue((string)result);
   if (result is int) return new IntValue((int)result);
   if (result is double) return new DoubleValue((double)result);
   if (result is bool) return new BoolValue((bool)result);
   return null;
 }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:35,代码来源:Calculator.cs

示例2: CalculateName

        public static string CalculateName(DirectoryInfo root, DirectoryInfo folder)
        {
            if (root.Root.FullName != folder.Root.FullName)
                throw new InvalidOperationException("Unrelated directories.");

            Stack<DirectoryInfo> rootList = new Stack<DirectoryInfo>();
            while (root.FullName != root.Root.FullName)
            {
                rootList.Push(root);
                root = root.Parent;
            }

            Stack<DirectoryInfo> itemList = new Stack<DirectoryInfo>();
            while (folder.FullName != folder.Root.FullName)
            {
                itemList.Push(folder);
                folder = folder.Parent;
            }

            while (rootList.Count != 0 && itemList.Count != 0 && rootList.Peek().Name == itemList.Peek().Name)
            {
                rootList.Pop();
                itemList.Pop();
            }

            if (rootList.Count != 0)
                throw new InvalidOperationException("Item is not contained in root.");

            if (itemList.Count == 0)
                return null;

            return String.Join("/", itemList.Select(item => item.Name));
        }
开发者ID:modulexcite,项目名称:managed-lzma,代码行数:33,代码来源:ArchiveWriter.cs

示例3: CheckMax

 private void CheckMax(Stack<Coordinate> coordinates)
 {
     int max = 1;
     var values = coordinates.Select(c => _data[c.X, c.Y]);
     values.ToList().ForEach(i => max *= i);
     if (max > Max) {
         Max = max;
         MaxCoor.Clear();
         MaxCoor.AddRange(coordinates.Reverse());
     }
 }
开发者ID:maartenoosterhoff,项目名称:ProjectEuler,代码行数:11,代码来源:ProblemSolver011.cs

示例4: getAllAnagrams

        private static void getAllAnagrams(string s, Stack<char> st, ref Node n)
        {
            if (s.Length <= 0)
            {
                // End of tree branch - flatten the stack and add it to Anagrams list.
                allAnagramsList.Add(st.Select(q => q).ToArray());
            }

            for (int i = 0; i < s.Length; i++)
            {
                if (n != null && !n.nodeList.Exists(x => x.value == s[i]))
                {
                    Node newnode = new Node();
                    newnode.value = s[i];
                    st.Push(s[i]);
                    n.nodeList.Add(newnode);
                    string temp = s.Remove(i, 1);
                    getAllAnagrams(temp, st, ref newnode);
                    st.Pop();
                }
            }
        }
开发者ID:kasha01,项目名称:Test-Dome,代码行数:22,代码来源:Program.cs

示例5: Tokenize


//.........这里部分代码省略.........
                    //open group
                    var token = m.Value.TrimStart('{').TrimEnd('}').TrimStart('#').Trim();
                    if (scopestack.Any() && scopestack.Peek().Item1 == token)
                    {
                        yield return new TokenPair(TokenType.ElementClose, Validated(token, templateString, m.Index, ref lines, ref parseErrors));
                    }
                    else
                    {
                        scopestack.Push(Tuple.Create(token, m.Index));
                    }
                    yield return new TokenPair(TokenType.ElementOpen, Validated(token, templateString, m.Index, ref lines, ref parseErrors));
                }
                else if (m.Value.StartsWith("{{^"))
                {
                    //open inverted group
                    var token = m.Value.TrimStart('{').TrimEnd('}').TrimStart('^').Trim();

                    if (scopestack.Any() && scopestack.Peek().Item1 == token)
                    {
                        yield return new TokenPair(TokenType.ElementClose, Validated(token, templateString, m.Index, ref lines, ref parseErrors));
                    }
                    else
                    {
                        scopestack.Push(Tuple.Create(token, m.Index));
                    }
                    yield return new TokenPair(TokenType.InvertedElementOpen, Validated(token, templateString, m.Index, ref lines, ref parseErrors));
                }
                else if (m.Value.StartsWith("{{/"))
                {
                    var token = m.Value.TrimStart('{').TrimEnd('}').TrimStart('/').Trim();
                    //close group
                    if (scopestack.Any() && scopestack.Peek().Item1 == token)
                    {
                        scopestack.Pop();
                        yield return new TokenPair(TokenType.ElementClose, Validated(token, templateString, m.Index, ref lines, ref parseErrors));
                    }
                    else
                    {
                        var location = HumanizeCharacterLocation(templateString, m.Index, ref lines);
                        parseErrors.Add(new IndexedParseException(location, "It appears that open and closing elements are mismatched."));
                    }
                }
                else if (m.Value.StartsWith("{{{") | m.Value.StartsWith("{{&"))
                {
                    //escaped single element
                    var token = m.Value.TrimStart('{').TrimEnd('}').TrimStart('&').Trim();
                    yield return new TokenPair(TokenType.UnescapedSingleValue, Validated(token, templateString, m.Index, ref lines, ref parseErrors));
                }
                else if (m.Value.StartsWith("{{!"))
                {
                    //it's a comment drop this on the floor, no need to even yield it.
                }
                else
                {
                    //unsingle value.
                    var token = m.Value.TrimStart('{').TrimEnd('}').Trim();
                    yield return new TokenPair(TokenType.EscapedSingleValue, Validated(token, templateString, m.Index, ref lines, ref parseErrors));
                }

                //move forward in the string.
                idx = m.Index + m.Length;
            }

            if (idx < templateString.Length)
            {
                yield return new TokenPair(TokenType.Content, templateString.Substring(idx));
            }

            #region Assert that any scopes opened must be closed.
            if (scopestack.Any())
            {
                var scopes = scopestack.Select(k =>
                {
                    var value = k.Item1.Trim('{', '#', '}');
                    if (value.StartsWith("each "))
                    {
                        value = value.Substring(5);
                    }
                    return new { scope = value, location = HumanizeCharacterLocation(templateString, k.Item2, ref lines) };
                }).Reverse()
                .ToArray();

                foreach (var unclosedScope in scopes)
                {
                    //var line = FindLineForLocation(templateString, m.Index, ref lines);
                    parseErrors.Add(new IndexedParseException(unclosedScope.location,
                        "A scope block to the following path was opened but not closed: '{0}', please close it using the appropriate syntax.",
                        unclosedScope.scope));
                }
            }
            #endregion

            //We want to throw an aggregate template exception, but in due time.
            if (parseErrors.Any())
            {
                var innerExceptions = parseErrors.OrderBy(k => k.LineNumber).ThenBy(k => k.CharacterOnLine).ToArray();
                throw new AggregateException(innerExceptions);
            }
            yield break;
        }
开发者ID:wildbit,项目名称:mustachio,代码行数:101,代码来源:Tokenizer.cs

示例6: Sort

        public IEnumerable<IBuildStep> Sort(IEnumerable<IBuildStep> buildSteps)
        {
            List<Node> nodeGraph = buildSteps.Select(buildStep => new Node(buildStep)).ToList();

            foreach (var node in nodeGraph)
            {
                var depends = (DependsOnAttribute[])Attribute.GetCustomAttributes(node.BuildStep.GetType(), typeof(DependsOnAttribute));
                var dependNodes = nodeGraph.Where(n => depends.Any(d => d.DependedOnStep == n.BuildStep.GetType()));

                var edges = dependNodes.Select(n => new Edge(node, n)).ToArray();
                node.OutgoingEdges.AddRange(edges);

                foreach (var edge in edges)
                    edge.DestinationNode.IncomingEdges.Add(edge);
            }

            var result = new Stack<Node>();
            var sourceNodes = new Stack<Node>(nodeGraph.Where(n => !n.IncomingEdges.Any()));
            while (sourceNodes.Count > 0)
            {
                var sourceNode = sourceNodes.Pop();
                result.Push(sourceNode);

                for (int i = sourceNode.OutgoingEdges.Count - 1; i >= 0; i--)
                {
                    var edge = sourceNode.OutgoingEdges[i];
                    edge.Remove();

                    if (!edge.DestinationNode.IncomingEdges.Any())
                        sourceNodes.Push(edge.DestinationNode);
                }
            }

            if (nodeGraph.SelectMany(n => n.IncomingEdges).Any())
                throw new CircularDependencyException();

            return result.Select(n => n.BuildStep);
        }
开发者ID:kevholditch,项目名称:BuilderFramework,代码行数:38,代码来源:BuildStepDependencySorter.cs

示例7: GetAllCombinationsWithSumS

        private static void GetAllCombinationsWithSumS(TreeNode<int> start, Stack<TreeNode<int>> stack, int currentSum, List<List<int>> res, int sum)
        {
            stack.Push(start);
            currentSum += start.Value;

            if (start.Children.Count == 0)
            {
                if (currentSum == sum)
                {
                    var r = stack.Select(x => x.Value).ToList();
                    res.Add(r);
                }
                return;
            }

            foreach (var child in start.Children)
            {
                GetAllCombinationsWithSumS(child, stack, currentSum, res, sum);
                stack.Pop();
            }
        }
开发者ID:NikolovNikolay,项目名称:Telerik-Homeworks,代码行数:21,代码来源:TreeManipulating.cs

示例8: sanitizer

        public static SanitizeResult sanitizer(String html, Regex allowedTags, Regex forbiddenTags)
        {
            SanitizeResult ret = new SanitizeResult();
            Stack<String> openTags = new Stack<string>();

            if (String.IsNullOrEmpty(html))
                return ret;

            List<String> tokens = tokenize(html);

            // -------------------   LOOP for every token --------------------------
            for (int i = 0; i < tokens.Count; i++)
            {
                String token = tokens[i];
                bool isAcceptedToken = false;

                Match startMatcher = tagStartPattern.Match(token);
                Match endMatcher = tagClosePattern.Match(token);

                //--------------------------------------------------------------------------------  COMMENT    <!-- ......... -->
                if (commentPattern.Match(token).Success)
                {
                    ret.val = ret.val + token + (token.EndsWith("-->") ? "" : "-->");
                    ret.invalidTags.Add(token + (token.EndsWith("-->") ? "" : "-->"));
                    continue;

                    //--------------------------------------------------------------------------------  OPEN TAG    <tag .........>
                }
                else if (startMatcher.Success)
                {

                    //tag name extraction
                    String tag = startMatcher.Groups[1].Value.ToLower();

                    //-----------------------------------------------------  FORBIDDEN TAG   <script .........>
                    if (forbiddenTags.Match(tag).Success)
                    {
                        ret.invalidTags.Add("<" + tag + ">");
                        continue;

                        // --------------------------------------------------  WELL KNOWN TAG
                    }
                    else if (allowedTags.Match(tag).Success)
                    {

                        String cleanToken = "<" + tag;
                        String tokenBody = startMatcher.Groups[2].Value;

                        //first test table consistency
                        //table tbody tfoot thead th tr td
                        if ("thead".Equals(tag) || "tbody".Equals(tag) || "tfoot".Equals(tag) || "tr".Equals(tag))
                        {
                            if (openTags.Select(t => t == "table").Count() <= 0)
                            {
                                ret.invalidTags.Add("<" + tag + ">");
                                continue;
                            }
                        }
                        else if ("td".Equals(tag) || "th".Equals(tag))
                        {
                            if (openTags.Count(t => t == "tr") <= 0)
                            {
                                ret.invalidTags.Add("<" + tag + ">");
                                continue;
                            }
                        }

                        // then test properties
                        //Match attributes = attributesPattern.Match(tokenBody);
                        var attributes = attributesPattern.Matches(tokenBody);

                        bool foundURL = false; // URL flag

                        foreach (Match attribute in attributes)
                        //while (attributes.find())
                        {
                            String attr = attribute.Groups[1].Value.ToLower();
                            String val = attribute.Groups[2].Value;

                            // we will accept href in case of <A>
                            if ("a".Equals(tag) && "href".Equals(attr))
                            {    // <a href="......">

                                try
                                {
                                    var url = new Uri(val);

                                    if (url.Scheme == Uri.UriSchemeHttp || url.Scheme == Uri.UriSchemeHttps || url.Scheme == Uri.UriSchemeMailto)
                                    {
                                        foundURL = true;
                                    }
                                    else
                                    {
                                        ret.invalidTags.Add(attr + " " + val);
                                        val = "";
                                    }
                                }
                                catch
                                {
                                    ret.invalidTags.Add(attr + " " + val);
//.........这里部分代码省略.........
开发者ID:ajorion,项目名称:Outils,代码行数:101,代码来源:htmlParser.cs

示例9: ParseInLineVariableOrMetadata


//.........这里部分代码省略.........
                                isProblem = true;

                                changedLanguage = true;
                            }
                        }
                        else
                        {
                            errorId = data.ErrorList.Count;
                            data.ErrorList.Add(
                                Markdown.GenerateError(
                                    Language.Message("BadLinkOrMissingMarkdownFile", pathToLinkedFile, variableName),
                                    MessageClass.Error,
                                    Markdown.Unescape(OnErrorStringToUseForMatch),
                                    errorId,
                                    data));

                            isProblem = true;
                            outString = OnErrorStringToUseForMatch;
                        }
                    }

                    if (linkedFileDir.Exists && linkedFileDir.GetFiles(string.Format("*.{0}.udn", languageForFile)).Length > 0)
                    {
                        currentFile = linkedFileDir.GetFiles(string.Format("*.{0}.udn", languageForFile))[0];
                    }
                }

                // Cycle detection mechanism. First check if there was request for that variable in the visited stack.
                var currentVisitedVariableTuple = new Tuple<string, string>(currentFile.FullName, variableName);
                if (visitedVariables != null && visitedVariables.Contains(currentVisitedVariableTuple))
                {
                    // cycle detected
                    visitedVariables.Push(currentVisitedVariableTuple);
                    string visitedVariablesMessage = string.Join(", ", visitedVariables.Select(
                            (v) =>
                            {
                                return string.Format("[{0}, {1}]", v.Item1, v.Item2);
                            }));
                    visitedVariables.Pop();

                    data.ErrorList.Add(
                        Markdown.GenerateError(Language.Message("CycleDetectedInVariableRefs", visitedVariablesMessage), MessageClass.Error,
                        "", data.ErrorList.Count, data));

                    return "";
                }

                if (!data.ProcessedDocumentCache.TryGetLinkedFileVariable(currentFile, variableName, out outString))
                {
                    if (doc.PerformStrictConversion())
                    {
                        //error
                        errorId = data.ErrorList.Count;
                        data.ErrorList.Add(
                            Markdown.GenerateError(
                                Language.Message("VariableOrMetadataNotFoundInFile", variableName, currentFile.FullName),
                                MessageClass.Error,
                                OnErrorStringToUseForMatch,
                                errorId,
                                data));

                        isProblem = true;
                    }
                    outString = OnErrorStringToUseForMatch.Replace("%", "&#37;");
                }
                else
开发者ID:Art1stical,项目名称:AHRUnrealEngine,代码行数:67,代码来源:VariableManager.cs

示例10: NameFromStack

 private static string NameFromStack(Stack<IAnalysisItemView> stack) {
     return string.Join(".", stack.Select(av => av.Name));
 }
开发者ID:jsschultz,项目名称:PTVS,代码行数:3,代码来源:ClassView.cs

示例11: Run

        public ITestResult Run(IIntent intent, ITestProvider provider)
        {
            if (provider.Ignored)
            return _resultFactory.CreateIgnoredTestResult(provider);

              _listener.OnTestStarted(intent);

              IOutputRecording outputRecording;
              var operationResults = new List<IOperationResult>();
              var cleanupProviderStack = new Stack<IOperationProvider>();
              var stopWatch = Stopwatch.StartNew();

              using (outputRecording = _resultFactory.CreateOutputRecording())
              {
            // TODO: Repetition with ContextRunner
            foreach (var operationProvider in provider.OperationProviders)
            {
              Trace.Assert(
              !cleanupProviderStack.Contains(operationProvider) || operationProvider == cleanupProviderStack.Pop(),
              string.Format("Cleanup ({0}) is not in order to setup.", operationProvider.Action));

              var operationResult = _operationRunner.Run(operationProvider);
              operationResults.Add(operationResult);

              if (operationResult.State == State.Failed && operationResult.Type != OperationType.Assertion)
            break;

              if (operationProvider.CleanupProvider != null)
            cleanupProviderStack.Push(operationProvider.CleanupProvider);
            }

            Trace.Assert(
            !cleanupProviderStack.Any() || operationResults.Any(x => x.State == State.Failed),
            "Either cleanup stack must be empty, or any result must have failed.");

            operationResults.AddRange(cleanupProviderStack.Select(_operationRunner.Run));
              }

              var result = _resultFactory.CreateTestResult(provider, stopWatch.Elapsed, outputRecording, operationResults);

              _listener.OnTestFinished(result);

              return result;
        }
开发者ID:igor-toporet,项目名称:TestFx,代码行数:44,代码来源:TestRunner.cs

示例12: ParseIntegerRange

        private IEnumerable<Node> ParseIntegerRange()
        {
            var intRes = new Stack<int>();
            var token = _tokens.Peek();
            while (!token.Lexeme.Equals(";"))
            {
                token = _tokens.Dequeue();
                var lexeme = token.Lexeme;
                if (",".Equals(lexeme))
                {
                    if (!intRes.Any())
                    {
                        _errors.Add(
                            new ParseError(
                                "Expected integer literal before ',' in reserved range ",
                                token));
                        return new List<Node>();
                    }
                    token = _tokens.Peek();
                    continue;
                }

                if (_parser.IsDecimalLiteral(lexeme))
                {
                    intRes.Push(int.Parse(lexeme));
                    token = _tokens.Peek();
                    continue;
                }

                if (!"to".Equals(lexeme))
                {
                    token = _tokens.Peek();
                    continue;
                }

                // So now we are looking ahead at the token after 'to', so we have something like '9 to 11'
                if (!intRes.Any()) // In the case that we found a 'to' but haven't yet found an integer
                {
                    _errors.Add(
                       new ParseError(
                           "Expected integer literal before 'to' in reserved range ",
                           token));
                    return new List<Node>();
                }

                var startRangeAt = intRes.Pop(); // Go get the last integer read, e.g. 9
                var nextToken = _tokens.Peek(); // Look ahead for the next integer, e.g. 11
                if (!_parser.IsDecimalLiteral(nextToken.Lexeme)) // If the next token isn't an integer create Error
                {
                    _errors.Add(
                        new ParseError(
                            "Expected integer literal after 'to' in reserved range ",
                            nextToken));
                    return new List<Node>();
                }

                // If we don't have an error go ahead and remove the token and use it to find the end range.
                nextToken = _tokens.Dequeue();
                var endRangeAt = int.Parse(nextToken.Lexeme);

                // Now push all the integers in the range onto the stack.
                var rangeLength = endRangeAt - startRangeAt + 1;
                foreach (var elem in Enumerable.Range(startRangeAt, rangeLength))
                {
                    intRes.Push(elem);
                }

                // If we've got this far, set the token for the While comparison to the next.
                token = _tokens.Peek();
            }

            // Now that we've hit an Endline or ';' terminator, return.
            return intRes.Select(t => new Node(NodeType.IntegerLiteral, t.ToString())).Reverse();
        }
开发者ID:mholo65,项目名称:ProtobufGenerator,代码行数:74,代码来源:SyntaxAnalyzer.cs

示例13: ConstructsFrames

        private static void ConstructsFrames(RunElementTreeNode thisNode, Stack<RunElementTreeNode> stack, Collection<RunFrame> frames, AbstractRunFrameFactory runFrameFactory)
        {
            if (thisNode == null)
            {
                throw new System.ArgumentNullException("thisNode");
            }

            if (stack == null)
            {
                throw new ArgumentNullException("stack");
            }

            if (frames == null)
            {
                throw new ArgumentNullException("frames");
            }

            if (runFrameFactory == null)
            {
                throw new ArgumentNullException("runFrameFactory");
            }

            stack.Push(thisNode);

            if (thisNode.FirstChild == null)
            {
                frames.Add(runFrameFactory.CreateFrame(stack.Select(node => node.Element)));
            }
            else
            {
                ConstructsFrames(thisNode.FirstChild, stack, frames, runFrameFactory);
            }

            stack.Pop();
            if (thisNode.Next != null)
            {
                ConstructsFrames(thisNode.Next, stack, frames, runFrameFactory);
            }
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:39,代码来源:RunFrameBuilder.cs

示例14: FindCircularDependencies

        public List<CircularDependency> FindCircularDependencies()
        {
            if(NodeDependencies.Count == 0)
                return null;

            var circularDependencies = new List<CircularDependency>();

            var stack = new Stack<NodeInfo>();
            stack.Push(new NodeInfo(this));

            while(stack.Any())
            {
                var current = stack.Peek().GetNextDependency();
                if(current != null)
                {
                    if(current.Node == this)
                    {
                        var nodes = stack.Select(info => info.Node);
                        circularDependencies.Add(new CircularDependency(nodes));
                    }
                    else
                    {
                        bool visited = stack.Any(info => info.Node == current.Node);
                        if(!visited)
                            stack.Push(current);
                    }
                }
                else
                {
                    stack.Pop();
                }
            }

            return circularDependencies;
        }
开发者ID:Robin--,项目名称:Warewolf,代码行数:35,代码来源:Node.cs

示例15: GetRelativePath

        /// <summary>
        /// Build the relative path in the same format that ZipArchive uses
        /// </summary>
        private static string GetRelativePath(DirectoryInfo root, FileInfo file)
        {
            var parents = new Stack<DirectoryInfo>();

            var parent = file.Directory;

            while (parent != null
                   && !StringComparer.OrdinalIgnoreCase.Equals(parent.FullName, root.FullName))
            {
                parents.Push(parent);
                parent = parent.Parent;
            }

            if (parent == null)
            {
                // the given file path does not appear under root
                throw new FileNotFoundException(file.FullName);
            }

            var parts = parents.Select(d => d.Name).Concat(new string[] { file.Name });

            return String.Join("/", parts);
        }
开发者ID:eerhardt,项目名称:NuGet3,代码行数:26,代码来源:PackageFolderReader.cs


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