本文整理汇总了C#中Stack.First方法的典型用法代码示例。如果您正苦于以下问题:C# Stack.First方法的具体用法?C# Stack.First怎么用?C# Stack.First使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Stack
的用法示例。
在下文中一共展示了Stack.First方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Convert
public IEnumerable<Inline> Convert(string markup)
{
var currentSection = new TextSection();
var effects = new Stack<TextSection>();
effects.Push(currentSection);
var currentString = new StringBuilder();
bool escaped = false;
foreach (var c in markup) {
if (escaped) {
currentString.Append(c);
escaped = false;
} else {
if(c=='\\'){
escaped = true;
continue;
}else{
// Look for an end tag
var endTextEffect = effects.First().Effect;
if (endTextEffect != null) {
char endTag = endTextEffect.EndTag;
if (endTag == c) {
SaveCurrentText(effects, currentString);
var finishedEffect = effects.Pop();
effects.First().Inners.Add(finishedEffect);
continue;
}
}
// Look for a new start tag
var startTextEffect = FindMatchingTextEffectStartTag(c);
if (startTextEffect != null) {
SaveCurrentText(effects, currentString);
effects.Push(new TextSection { Effect = startTextEffect });
continue;
} else {
// otherwise, just add it to the current string.
currentString.Append(c);
}
}
}
}
SaveCurrentText(effects, currentString);
var rootEffect = effects.Pop();
return rootEffect.Inners.CreateInlines();
}
示例2: ReadJson
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var nav = new Stack<NavigationItems>();
var baseItem = new NavigationItems();
nav.Push(baseItem);
string name = string.Empty;
while (reader.Read())
{
if (reader.TokenType == JsonToken.EndObject)
{
if (nav.Count==1)
{
break;
}
nav.Pop();
continue;
}
// read display text
var tokenType = reader.TokenType;
if (reader.TokenType == JsonToken.PropertyName)
{
name = (reader.Value as string) ?? string.Empty;
}
// progress to link or collection
reader.Read();
if (reader.TokenType == JsonToken.StartObject)
{
var coll = new NavigationItems();
coll.DisplayText = name;
nav.First().Items.Add(coll);
nav.Push(coll);
}
else if (reader.TokenType == JsonToken.String)
{
var item = new NavigationItem();
item.DisplayText = name;
item.Url = new Uri(reader.Value as string, UriKind.RelativeOrAbsolute);
nav.First().Items.Add(item);
}
}
return baseItem;
}
示例3: SaveCurrentText
static void SaveCurrentText(Stack<TextSection> effects, StringBuilder currentString)
{
// save off the text that's been saved so far
var text = currentString.ToString();
if (!String.IsNullOrEmpty(text))
effects.First().Inners.Add(new Text(text));
currentString.Clear();
}
示例4: Load
/// <summary>
/// Loads a snippet from XML.
/// </summary>
/// <param name="reader">The xml reader.</param>
/// <returns>The loaded snippet.</returns>
public static HtmlElement Load(XmlReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
HtmlElement top = null;
Stack<HtmlElement> stack = new Stack<HtmlElement>();
while (reader.NodeType != XmlNodeType.Element)
{
if (!reader.Read())
{
throw new XmlException("Element expected.");
}
}
top = CreateElement(reader.Name);
stack.Push(top);
while (stack.Count > 0 && reader.Read())
{
ContainerBodyHtmlElement current = stack.First() as ContainerBodyHtmlElement;
if (current != null)
{
switch (reader.NodeType)
{
case XmlNodeType.Text:
{
Html.EncodedText text = new Html.EncodedText(reader.Value);
current.Elements.Add(text);
}
break;
case XmlNodeType.Element:
{
HtmlElement child = CreateElement(reader.Name);
if (child is IBodyHtmlNode)
{
current.Elements.Add((IBodyHtmlNode)child);
stack.Push(child);
}
}
break;
case XmlNodeType.EndElement:
{
stack.Pop();
}
break;
}
}
}
return top;
}
示例5: ProcessOperators
/// <summary>
/// Process operators
/// </summary>
/// <param name="st">Expressions</param>
/// <param name="element">Operator element</param>
/// <param name="top">Top operator</param>
public void ProcessOperators(Stack<IExpression> st, OperatorExpression element, OperatorExpression top)
{
while (st.Count > 0 && Precedence(element) >= Precedence(top))
{
IExpression p = st.Pop();
if ((p as OperatorExpression).OperatorType == TokenType.OPENPAREN)
break;
converted.Add(p);
if (st.Count > 0)
top = st.First() as OperatorExpression;
}
}
示例6: CombinePath
private static string CombinePath(Stack<string> path)
{
var parts = new List<string>(3);
parts.Add(path.First());
if (path.Count > 1)
{
if (path.Count > 2)
{
parts.Add("..");
}
parts.Add(path.Last());
}
return string.Join(Path.DirectorySeparatorChar.ToString(), parts);
}
示例7: GetFormattedXml
public static string GetFormattedXml(this ConfigXmlDocument config, string indent = " ")
{
const string newline = "\n";
var lastElement = "";
var stack = new Stack<string>();
var builder = new StringBuilder();
var elements = config.InnerXml.Split(new[] { '<' }, StringSplitOptions.RemoveEmptyEntries)
.Where(n => !string.IsNullOrWhiteSpace(n))
.Select(n => string.Format("<{0}", n).Trim())
.ToArray();
foreach (var element in elements)
{
// append newline only when last line ends with >
if (builder.ToString().EndsWith(">"))
builder.Append(newline);
// append element to builder
builder.Append(element);
// push non-closing element onto builder
if (!element.StartsWith("</")) stack.Push(element);
// when there is only 1 element in the stack, continue
if (stack.Count == 1) continue;
// apply indentation
if (string.IsNullOrWhiteSpace(lastElement) || lastElement.EndsWith(">"))
for (var i = 0; i < stack.Count - 1; i++)
builder.Insert(builder.Length - element.Length, indent);
// self-closing elements and comments get popped off the stack
if (element.StartsWith("</")
|| element.StartsWith("<!--")
|| stack.First().EndsWith("/>"))
stack.Pop();
lastElement = element;
}
var result = builder.ToString();
return result;
}
示例8: AppendHTML
public override void AppendHTML(StringBuilder builder, Stack<EMInclude> includesStack, TransformationData data)
{
if (includesStack.Count > 0 && !includesStack.First().IncludeTOC)
{
return;
}
var isLocalTOC = linkedDocument == Document.TransformationData.Document;
builder.Append(RenderTOC(
startLevel,
endLevel,
string.IsNullOrWhiteSpace(path)
? ""
: Path.Combine(
data.CurrentFolderDetails.RelativeHTMLPath,
data.CurrentFolderDetails.Language,
path,
"index.html"),
!isLocalTOC));
}
示例9: getConvexHull
public static List<PointF> getConvexHull(List<PointF> points)
{
// Select points that has lowest X, than select point that has lowest Y -> must be one on the convex hull's
IEnumerable<PointF> smallestXs = points.Where(point => point.X == points.Min(p => p.X));
PointF leftMost = smallestXs.Where(point => point.Y == smallestXs.Min(p => p.Y)).First();
var tempo = points.FindAll(t => !t.Equals(leftMost));
tempo.Sort(delegate (PointF p1, PointF p2)
{
// Compare the sin(alpha)
// Point that make with leftmost and x-axis larger sin(alpha) will be considered first
if (cotWithX(leftMost, p1) < cotWithX(leftMost, p2))
return -1;
if (cotWithX(leftMost, p1) > cotWithX(leftMost, p2))
return 1;
// If alphas are equals, compare the distance between leftmost and p1, p2
// We want the point that has better chance to be on convex hull to go first
return (int)(Math.Pow(p2.X - leftMost.X, 2) + Math.Pow(p2.Y - leftMost.Y, 2) - (Math.Pow(p1.X - leftMost.X, 2) + Math.Pow(p1.Y - leftMost.Y, 2)))
;
});
Stack<PointF> convexHulls = new Stack<PointF>();
convexHulls.Push(leftMost);
foreach (PointF p in tempo)
{
FixConvexHull(leftMost, convexHulls, p);
if (cotWithX(leftMost, convexHulls.First()) != cotWithX(leftMost, p))
{
convexHulls.Push(p);
}
};
return convexHulls.ToList();
}
示例10: findLargestPrimeFactor
public static long findLargestPrimeFactor(long targetMultiple)
{
List<long> primes = new List<long>();
Stack<long> primeFactors = new Stack<long>();
long sqrt = Convert.ToInt64(Math.Ceiling(Math.Sqrt(targetMultiple)));
//seed list of numbers
for (long i = 2; i <= sqrt; i++)
{
if (validatePrime(primes, i))
{
primes.Add(i);
if (targetMultiple % i == 0)
{
primeFactors.Push(i);
}
}
}
return primeFactors.First<long>(); //counter-intuitive. Last prime is on top
}
示例11: ConvertFromInfixToPostFix
/// <summary>
/// Convert from infix to postfix
/// </summary>
/// <param name="e">Expressions</param>
/// <returns>Expressions in postfix</returns>
public List<IExpression> ConvertFromInfixToPostFix(List<IExpression> e)
{
List<IExpression> stack1 = new List<IExpression>(e);
Stack<IExpression> st = new Stack<IExpression>();
for (int i = 0; i < stack1.Count; i++)
{
IExpression element = stack1[i];
if (element.GetType() == typeof(OperatorExpression))
{
if (st.Count == 0 ||
(element as OperatorExpression).OperatorType == TokenType.OPENPAREN)
st.Push(element);
else
{
IExpression top = st.First();
if ((element as OperatorExpression).OperatorType == TokenType.CLOSEPAREN)
ProcessOperators(st, element as OperatorExpression, top as OperatorExpression);
else if (Precedence(element as OperatorExpression) < Precedence(top as OperatorExpression))
st.Push(element);
else
{
ProcessOperators(st, element as OperatorExpression, top as OperatorExpression);
st.Push(element);
}
}
}
else
converted.Add(element);
}
while (st.Count > 0)
{
IExpression b1 = st.Pop();
converted.Add(b1);
}
return converted;
}
示例12: Convert
private static string Convert(string pythonCode)
{
StringBuilder output = new StringBuilder();
Stack<int> indentStack = new Stack<int>(new[] { 0 });
LogicalLine currentLine = null;
int lineNumber = 0;
int blankLineCount = 0;
foreach (string physicalLine in pythonCode.Split('\n'))
{
lineNumber++;
if (currentLine == null || currentLine.IsComplete)
{
currentLine = new LogicalLine(lineNumber, physicalLine);
}
else
{
currentLine.Append(physicalLine);
}
if (currentLine.IsComplete)
{
if (currentLine.IsBlank)
{
// Blank lines have no effect on indentation levels
// Store them up, rather than rendering inline, because we want them to appear after any braces
blankLineCount++;
}
else
{
if (currentLine.IndentDepth > indentStack.First())
{
output.AppendLine("{".PadLeft(indentStack.First() + 1));
indentStack.Push(currentLine.IndentDepth);
}
else
{
while (currentLine.IndentDepth != indentStack.First())
{
indentStack.Pop();
output.AppendLine("}".PadLeft(indentStack.First() + 1));
}
}
while (blankLineCount > 0)
{
output.AppendLine();
blankLineCount--;
}
output.AppendLine(currentLine.Text);
}
}
}
// Close off braces at end of file
while (indentStack.Count > 1)
{
indentStack.Pop();
output.AppendLine("}".PadLeft(indentStack.First() + 1));
}
return output.ToString();
}
示例13: Evaluate
public bool Evaluate(Transaction tx = null, UInt32 txInIndex = 0)
{
Stack<IfElseExec> ifExec = new Stack<IfElseExec>();
int lastCodeSeperator = 0;
stack.Clear();
altstack.Clear();
for (int index = 0; index < elements.Count; index++)
{
ScriptElement se = elements[index];
if (ifExec.Count > 0)
if ((ifExec.First() == IfElseExec.SKIP_IF && !(se.opCode == OpCode.OP_ELSE || se.opCode == OpCode.OP_ENDIF)) ||
(ifExec.First() == IfElseExec.SKIP_ELSE && !(se.opCode == OpCode.OP_ENDIF)))
continue;
if (se.isData)
{
stack.Push(se.data);
continue;
}
switch (se.opCode)
{
case OpCode.OP_RESERVED:
{
return false;
}
case OpCode.OP_NOP:
{
// NOP, Dump stack for debug
/*
stack.ToList().ForEach(x => Console.WriteLine(HexString.FromByteArray(x)));
Console.WriteLine("---------------------------");
*/
break;
}
case OpCode.OP_VER:
{
return false;
}
case OpCode.OP_IF:
case OpCode.OP_NOTIF:
{
if (stack.Count < 1)
return false;
Boolean stackIsZero = new ScriptVarInt(stack.Pop()).value.IsZero;
if ((se.opCode == OpCode.OP_IF && !stackIsZero) || (se.opCode == OpCode.OP_NOTIF && stackIsZero))
{
// Run to else or endif
ifExec.Push(IfElseExec.RUN_IF);
}
else
{
// Skip to else or endif
ifExec.Push(IfElseExec.SKIP_IF);
}
break;
}
case OpCode.OP_VERIF:
case OpCode.OP_VERNOTIF:
{
return false;
}
case OpCode.OP_ELSE:
{
if (ifExec.Count == 0)
// No preceding if statement!
return false;
if (ifExec.First() == IfElseExec.RUN_IF)
{
// If ran, skip else
ifExec.Push(IfElseExec.SKIP_ELSE);
}
else if (ifExec.First() == IfElseExec.SKIP_IF)
{
// If did not run, run else
ifExec.Push(IfElseExec.RUN_ELSE);
}
break;
}
case OpCode.OP_ENDIF:
{
if (ifExec.Count == 0)
// No preceding if statement!
return false;
if (ifExec.First() == IfElseExec.RUN_IF ||
ifExec.First() == IfElseExec.SKIP_IF)
{
ifExec.Pop();
}
else if (ifExec.First() == IfElseExec.RUN_ELSE ||
ifExec.First() == IfElseExec.SKIP_ELSE)
{
ifExec.Pop();
ifExec.Pop();
}
break;
}
case OpCode.OP_VERIFY:
//.........这里部分代码省略.........
示例14: StackExtensions_First_ThrowsExceptionIfStackIsEmpty
public void StackExtensions_First_ThrowsExceptionIfStackIsEmpty()
{
var stack = new Stack<Int32>();
stack.First();
}
示例15: calculation
public void calculation()
{
Stack<string> valStack = new Stack<string>();
if (polishRecord.Count() > 0)
{
stackToString();
string first, temp;
Regex num = new Regex("[\\.0-9]");
Regex trig = new Regex("[wxyz]");
while (polishRecord.Count() > 0)
{
first = polishRecord.First();
polishRecord.RemoveAt(0);
if (num.IsMatch(first))
{
valStack.Push(first);
}
else
{
if (valStack.Count() > 1 && !(trig.IsMatch(first)))
{
temp = ariphCalculation(first, valStack.ElementAt(1).Replace(".", ","), valStack.ElementAt(0).Replace(".", ","));
valStack.Pop();
valStack.Pop();
valStack.Push(temp.Replace(",", "."));
}
else if (valStack.Count() > 0)
{
if (trig.IsMatch(first))
{
temp = trigCalculation(first, valStack.First().Replace(".", ","));
valStack.Pop();
valStack.Push(temp.Replace(",", "."));
}
else
{
MessageBox.Show("Неверно записана операция\nВыводимое значение так же неверно", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}
else
{
MessageBox.Show("Неверно записана операция\nВыводимое значение так же неверно", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}
}
double res = 0;
try
{
res = Convert.ToDouble(valStack.Pop().Replace(".", ","));
}
catch (InvalidOperationException)
{
MessageBox.Show("Отсутствуют операнды", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (valStack.Count() > 0)
MessageBox.Show("Неверно записана операция\nВыводимое значение так же неверно", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
result = res.ToString("F2").Replace(",", ".");
}
else
{
MessageBox.Show("Неверно записана операция\nНечего вычислять", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}