本文整理汇总了C#中Queue.Select方法的典型用法代码示例。如果您正苦于以下问题:C# Queue.Select方法的具体用法?C# Queue.Select怎么用?C# Queue.Select使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Queue
的用法示例。
在下文中一共展示了Queue.Select方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ChaveamentoCircular
/// <summary>
/// Método responsável por simular um chaveamento circular sem o uso de Thread ou Task
/// quantum: Recebe a média de todos os tempos.
/// filaDeProcesso: Faz uma fila com os valores da lista de tarefa.
/// emExecução: é a tarefa a ser executada no momento.
/// </summary>
/// <param name="Tarefas">É uma lista de todas tarefas que serão executadas.</param>
/// <returns>Retorna a lista dos objetos escalonados.</returns>
public List<ITarefa> ChaveamentoCircular(List<ITarefa> Tarefas)
{
double quantum = Tarefas.Select(item => item.TempoDuracao).Average();
var filaDeProcesso = new Queue<ITarefa>(Tarefas);
ITarefa emExecucao;
do
{
emExecucao = filaDeProcesso.Peek();
if ((emExecucao.TempoDuracao - quantum) < 0)
{
Thread.Sleep(1000);
emExecucao.TempoDuracao = 0;
Console.WriteLine($"O processo {emExecucao.Identificador} foi completado!");
filaDeProcesso.Dequeue();
}
else if((emExecucao.TempoDuracao - quantum) > 0)
{
Thread.Sleep(1000);
emExecucao.TempoDuracao = emExecucao.TempoDuracao - quantum;
Console.WriteLine($"O {emExecucao.Identificador} necessita de mais {emExecucao.TempoDuracao} segundos para sua finalização!");
filaDeProcesso.Enqueue(emExecucao);
filaDeProcesso.Dequeue();
}
} while (filaDeProcesso.Select(item => item.TempoDuracao).All(item => item == 0));
return new List<ITarefa>(filaDeProcesso);
}
示例2: OrderByDependencies
public virtual IConfiguration[] OrderByDependencies(IEnumerable<IConfiguration> configurations)
{
var processQueue = new Queue<ConfigItem>(configurations.Select(config => new ConfigItem(config, configurations)));
var added = new HashSet<string>();
List<IConfiguration> result = new List<IConfiguration>();
int iterationCount = 0;
while (processQueue.Count > 0 && iterationCount < MaxIterations)
{
iterationCount++;
var current = processQueue.Dequeue();
// not all dependencies of the current item are added. Push it back onto the queue, and we'll pick it up later.
if (!current.Dependencies.All(dep => added.Contains(dep.Name)))
{
processQueue.Enqueue(current);
continue;
}
result.Add(current.Config);
added.Add(current.Config.Name);
}
if (iterationCount == MaxIterations) throw new InvalidOperationException("There is a dependency loop in your Unicorn configuration dependencies. Unresolved configurations: " + string.Join(", ", processQueue.Select(x => x.Config.Name)));
return result.ToArray();
}
示例3: Rohdaten
public Rohdaten(Queue<Kommunikator.armRecVal> precDataCopy)
{
InitializeComponent();
recDataPointer = precDataCopy;
recDataCopy = new List<Kommunikator.armRecVal>(precDataCopy.Select(x => x.Clone()).Cast<Kommunikator.armRecVal>());
recDataCopy.Sort();
bs.DataSource = recDataCopy;
dgvRecData.DataSource = bs;
}
示例4: OperationToElements_validOperationString_ElementsInQueue
public void OperationToElements_validOperationString_ElementsInQueue()
{
var calc = new Calculator();
var result = calc.OperationToElements("3+2");
var expectation = new Queue<OperationElement>();
expectation.Enqueue(new OperationElement(OperationElementType.NUMBER,"3"));
expectation.Enqueue(new OperationElement(OperationElementType.OPERATOR, "+"));
expectation.Enqueue(new OperationElement(OperationElementType.NUMBER, "2"));
Assert.AreEqual(expectation.Select(r => r.ToTestValue()), result.Select(r => r.ToTestValue()));
}
示例5: EnumerateByFrequencies
static void EnumerateByFrequencies(WaveReader originalReader, WaveReader compressedReader, int numChannels, int windowSize, float samplesPerCheck, Dictionary<int, Action<float[], float[]>> comparisonMethods, long compressedSamplesToSkip)
{
originalReader.Seek(0);
compressedReader.Seek(compressedSamplesToSkip);
var fft = new ComplexFourierTransformation();
var originalQueue = new Queue<float[]> ();
var compressedQueue = new Queue<float[]> ();
using (var compressedSamplesItr = compressedReader.ReadAllSamples_Float ().GetEnumerator ())
{
foreach (var originalSamples in originalReader.ReadAllSamples_Float ())
{
if (compressedSamplesItr.MoveNext ())
{
originalQueue.Enqueue (originalSamples);
compressedQueue.Enqueue (compressedSamplesItr.Current);
if (originalQueue.Count == windowSize)
{
for (var channelCtr = 0; channelCtr < numChannels; channelCtr++)
{
var originalSamplesToTransform = originalQueue.Select (s => new Complex (s [channelCtr], 0)).ToArray ();
var compressedSamplesToTransform = compressedQueue.Select (s => new Complex (s [channelCtr], 0)).ToArray ();
fft.TransformForward (originalSamplesToTransform);
fft.TransformForward (compressedSamplesToTransform);
foreach (var kvp in comparisonMethods)
{
var fftIndex = kvp.Key;
var comparisonMethod = kvp.Value;
comparisonMethod(
new float[] { Convert.ToSingle (originalSamplesToTransform [fftIndex].Modulus) },
new float[] { Convert.ToSingle (compressedSamplesToTransform [fftIndex].Modulus) });
}
}
for (var ctr = 0; ctr < samplesPerCheck; ctr++)
{
originalQueue.Dequeue ();
compressedQueue.Dequeue ();
}
}
}
else
{
Console.WriteLine ("Compressed file is shorter");
break;
}
}
if (compressedSamplesItr.MoveNext ())
{
Console.WriteLine ("Compressed file is longer");
}
}
}
示例6: RunPackageQueue
/// <summary>
/// Process the package queue.
/// </summary>
public void RunPackageQueue()
{
// Sort by action (uninstall/purge => install/update => configure)
_pendingPackages.Sort(
(a, b) => ((byte)a.Item1).CompareTo((byte)b.Item1));
var pending = new Queue<Tuple<PackageAction, Package>>(_pendingPackages);
_pendingPackages.Clear();
while (pending.Any())
{
var item = pending.Dequeue();
var action = item.Item1;
var package = item.Item2;
switch (action)
{
case PackageAction.Install:
if (ProfileInfo.InstalledPackages.Any(p => p.Id == package.Metadata.Id && p.State.HasFlag(InstalledPackageState.Installed)))
throw new InvalidOperationException(string.Format("Package {0} already installed.",
item.Item2.Metadata.Id));
foreach (var dep in package.Metadata.Dependencies)
{
Debug.WriteLine("Analyzing {0}: {1}", dep.Type.ToString().ToLower(),
dep.Name + " " + dep.Versions);
switch (dep.Type)
{
case DependencyType.Prerequirement:
if (!HasMatchingInstalledPackages(dep))
{
throw new InvalidOperationException(
string.Format(
"Package {0} needs dependency {1} (versions {2}) to be pre-installed. You need to install the dependency before installing this package.",
item.Item2.Metadata.Id, dep.Name, dep.Versions));
}
break;
case DependencyType.Requirement:
if (!HasMatchingInstalledPackages(dep) &&
!PackageComparison.GetMatches(pending.Select(t => t.Item2), p => p.Metadata.Id,
p => p.Metadata.Version, dep).Any())
{
throw new InvalidOperationException(
string.Format(
"Package {0} needs dependency {1} (versions {2}) to be installed with it. Append the dependency before installing this package.",
item.Item2.Metadata.Id, dep.Name, dep.Versions));
}
break;
case DependencyType.Incompatibility:
if (HasMatchingInstalledPackages(dep) &&
!PackageComparison.GetMatches(pending.Select(t => t.Item2), p => p.Metadata.Id,
p => p.Metadata.Version, dep).Any())
{
throw new InvalidOperationException(
string.Format(
"Package {0} is incompatible with {1} (versions {2}). Remove the incompatible package before installing this package.",
item.Item2.Metadata.Id, dep.Name, dep.Versions));
}
break;
}
}
Console.WriteLine("{2} {0} {1}...", package.Metadata.Id, package.Metadata.Version, "Installing");
break;
case PackageAction.Uninstall:
if (!ProfileInfo.InstalledPackages.Any(p => p.Id == package.Metadata.Id &&
Equals(p.Version, package.Metadata.Version) && p.State == (InstalledPackageState.Configured | InstalledPackageState.Installed)))
throw new InvalidOperationException(string.Format("Package {0} not installed and configured.",
item.Item2.Metadata.Id));
if (GetDependingInstalledPackages(package).Any())
throw new InvalidOperationException(
string.Format(
"Some of the installed packages depend on the package {0} which is marked to be uninstalled. Uninstall all depending packages first.",
item.Item2.Metadata.Id));
Console.WriteLine("{2} {0} {1}...", package.Metadata.Id, package.Metadata.Version,
"Uninstalling");
break;
case PackageAction.Purge:
if (!ProfileInfo.InstalledPackages.Any(p => p.Id == package.Metadata.Id &&
Equals(p.Version, package.Metadata.Version) && p.State == (InstalledPackageState.Configured | InstalledPackageState.Installed)))
throw new InvalidOperationException(string.Format("Package {0} not installed and configured.",
item.Item2.Metadata.Id));
if (GetDependingInstalledPackages(package).Any())
throw new InvalidOperationException(
string.Format(
"Some of the installed packages depend on the package {0} which is marked to be uninstalled. Uninstall all depending packages first.",
item.Item2.Metadata.Id));
Console.WriteLine("{2} {0} {1}...", package.Metadata.Id, package.Metadata.Version, "Purging");
break;
case PackageAction.Update:
if (ProfileInfo.InstalledPackages.All(p => p.Id != package.Metadata.Id && p.State == (InstalledPackageState.Configured | InstalledPackageState.Installed)))
throw new InvalidOperationException(string.Format("Package {0} not installed and configured.",
item.Item2.Metadata.Id));
if (ProfileInfo.InstalledPackages.Any(p => p.Id == package.Metadata.Id &&
Equals(p.Version, package.Metadata.Version)))
throw new InvalidOperationException(
//.........这里部分代码省略.........
示例7: UpSample
static IEnumerable<IEnumerable<float>> UpSample(WaveReader reader, int windowSize)
{
var fft = new MathNet.Numerics.Transformations.ComplexFourierTransformation ();
var determineVolumeSource = new Complex[]
{
new Complex(1, 0),
new Complex(1, 0),
new Complex(1, 0),
new Complex(1, 0),
};
fft.TransformForward(determineVolumeSource);
var determineVolumeDestination = new Complex[windowSize];
determineVolumeDestination[0] = determineVolumeSource[0];
for (var sampleCtr = 1; sampleCtr < windowSize; sampleCtr++)
determineVolumeDestination[sampleCtr] = Complex.FromModulusArgument(0,0);
fft.TransformBackward(determineVolumeDestination);
var multiplier = determineVolumeDestination[0].Real;
var sampleQueue = new Queue<float[]>();
for (var sampleCtr = 0; sampleCtr < 2; sampleCtr++)
sampleQueue.Enqueue(new float[reader.NumChannels]);
foreach (var samples in reader.ReadAllSamples_Float().Select(s => s.ToArray()))
{
sampleQueue.Enqueue(samples);
if (sampleQueue.Count == 4)
{
var expanded = new float[windowSize / 2][];
for (var ctr = 0; ctr < windowSize / 2; ctr++)
expanded[ctr] = new float[reader.NumChannels];
for (var channelCtr = 0; channelCtr < reader.NumChannels; channelCtr++)
{
var samplesToTransform = sampleQueue.Select(s => new Complex (s[channelCtr], 0)).ToArray();
fft.TransformForward (samplesToTransform);
var samplesToTransformBack = new Complex[windowSize];
samplesToTransformBack[0] = samplesToTransform[0];
samplesToTransformBack[1] = samplesToTransform[1];
samplesToTransformBack[1].Modulus /= 2;
samplesToTransformBack[samplesToTransformBack.Length - 1] = samplesToTransform[1];
samplesToTransformBack[samplesToTransformBack.Length - 1].Modulus /= 2;
samplesToTransformBack[samplesToTransformBack.Length - 1].Argument *= -1;
for (var ctr = 2; ctr < samplesToTransformBack.Length - 1; ctr++)
samplesToTransformBack[ctr] = Complex.FromModulusArgument(0, 0);
fft.TransformBackward(samplesToTransformBack);
for (var ctr = 0; ctr < windowSize / 2; ctr++)
expanded[ctr][channelCtr] = Convert.ToSingle(samplesToTransformBack[ctr + windowSize / 4].Real / multiplier);
}
foreach (var simplified in expanded)
yield return simplified;
sampleQueue.Dequeue();
sampleQueue.Dequeue();
}
}
}
示例8: DownSample
public static IEnumerable<float[]> DownSample(IEnumerable<float[]> samplesEnumerator, int numChannels, int windowSize, Action<float[]> highSampleCallback)
{
var fft = new MathNet.Numerics.Transformations.ComplexFourierTransformation ();
var determineVolumeSource = new Complex[windowSize];
for (var sampleCtr = 0; sampleCtr < windowSize; sampleCtr++)
determineVolumeSource[sampleCtr] = new Complex(1, 0);
fft.TransformForward(determineVolumeSource);
var determineVolumeDestination = new Complex[]
{
determineVolumeSource[0],
Complex.FromModulusArgument(0,0),
Complex.FromModulusArgument(0,0),
Complex.FromModulusArgument(0,0)
};
fft.TransformBackward(determineVolumeDestination);
var dcMultiplier = determineVolumeDestination[0].Modulus;
var ratio = (1d / Convert.ToDouble(windowSize)) * 2d * Math.PI;
for (var sampleCtr = 0; sampleCtr < windowSize; sampleCtr++)
{
var sampleCtrDouble = Convert.ToDouble(sampleCtr);
determineVolumeSource[sampleCtr] = new Complex(Math.Cos(sampleCtrDouble * ratio), 0);
}
fft.TransformForward(determineVolumeSource);
determineVolumeDestination = new Complex[]
{
Complex.FromModulusArgument(0,0),
determineVolumeSource[1],
Complex.FromModulusArgument(0,0),
determineVolumeSource[determineVolumeSource.Length - 1],
};
fft.TransformBackward(determineVolumeDestination);
var midMultiplier = determineVolumeDestination.Select(s => s.Modulus).Max();
/*// This only works when windowsize is 8
for (var sampleCtr = 0; sampleCtr < windowSize; sampleCtr++)
{
var abs = sampleCtr % 2 == 1 ? 1 : 0;
var sign = sampleCtr % 4 > 1 ? 1 : -1;
determineVolumeSource[sampleCtr] = new Complex(abs * sign, 0);
}*/
ratio = (1d / Convert.ToDouble(windowSize)) * 4d * Math.PI;
for (var sampleCtr = 0; sampleCtr < windowSize; sampleCtr++)
{
var sampleCtrDouble = Convert.ToDouble(sampleCtr);
determineVolumeSource[sampleCtr] = new Complex(Math.Cos(sampleCtrDouble * ratio), 0);
}
fft.TransformForward(determineVolumeSource);
determineVolumeDestination = new Complex[]
{
Complex.FromModulusArgument(0,0),
Complex.FromModulusArgument(0,0),
determineVolumeSource[2],
Complex.FromModulusArgument(0,0),
};
fft.TransformBackward(determineVolumeDestination);
var highMultiplier = determineVolumeDestination.Select(s => s.Modulus).Max();
var sampleQueue = new Queue<float[]>();
for (var sampleCtr = 0; sampleCtr < windowSize / 4; sampleCtr++)
sampleQueue.Enqueue(new float[numChannels]);
var maxOriginalSample = 0.0;
var maxLowFrequencySample = 0.0;
using (var sampleEnumerator = samplesEnumerator.GetEnumerator())
{
int samplesFromSource;
do
{
samplesFromSource = 0;
while (sampleQueue.Count < windowSize)
{
if (sampleEnumerator.MoveNext())
{
sampleQueue.Enqueue(sampleEnumerator.Current.ToArray());
samplesFromSource++;
}
else
sampleQueue.Enqueue(new float[numChannels]);
}
var simplified = new float[][]
{
//.........这里部分代码省略.........
示例9: OperationElementsToONP_validOperationElements_ElementsInONPQueue3
public void OperationElementsToONP_validOperationElements_ElementsInONPQueue3()
{
var calc = new Calculator();
var operationElements = new Queue<OperationElement>();
operationElements = calc.OperationToElements("(2+3)*5");
var expectation = new Queue<OperationElement>();
expectation.Enqueue(new OperationElement(OperationElementType.NUMBER, "2"));
expectation.Enqueue(new OperationElement(OperationElementType.NUMBER, "3"));
expectation.Enqueue(new OperationElement(OperationElementType.OPERATOR, "+"));
expectation.Enqueue(new OperationElement(OperationElementType.NUMBER, "5"));
expectation.Enqueue(new OperationElement(OperationElementType.OPERATOR, "*"));
var result = calc.OperationElementsToONP(operationElements);
Assert.AreEqual(expectation.Select(r => r.ToTestValue()), result.Select(r => r.ToTestValue()));
}
示例10: ScanDirectoryAsync
/// <summary>
/// Asynchronously scans a directory for viruses, optionally recursing into subdirectories.
/// </summary>
/// <param name="engine">ClamAV engine instance.</param>
/// <param name="path">Path to scan.</param>
/// <param name="options">Scan options.</param>
/// <param name="recurse">Whether to enter subdirectories.</param>
/// <param name="maxDepth">Maximum depth to scan, or zero for unlimited.</param>
/// <returns>The task object representing the asynchronous operation. The Result property on the task returns the scan results.</returns>
public static async Task<IEnumerable<FileScanResult>> ScanDirectoryAsync(this ClamEngine engine, string path, ScanOptions options, bool recurse, int maxDepth)
{
var scanQueue = new Queue<string>();
var pathStack = new Stack<Tuple<string /* path */, int /* depth */>>();
// Push the starting directory onto the stack.
pathStack.Push(Tuple.Create(path, 1));
while (pathStack.Count > 0)
{
var stackState = pathStack.Pop();
var currentPath = stackState.Item1;
var currentDepth = stackState.Item2;
var attributes = File.GetAttributes(currentPath);
// If we're in a directory, push all files and subdirectories to the stack.
if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
// Check if we're not about to go too deep.
if (maxDepth == 0 || currentDepth < maxDepth)
{
var subFiles = Directory.GetFiles(currentPath);
foreach (var file in subFiles)
{
pathStack.Push(Tuple.Create(file, currentDepth + 1));
}
var subDirectories = Directory.GetDirectories(currentPath);
foreach (var directory in subDirectories)
{
pathStack.Push(Tuple.Create(directory, currentDepth + 1));
}
}
}
// If this is a file, enqueue it for scanning.
else
{
scanQueue.Enqueue(currentPath);
}
}
var scanTasks = scanQueue.Select(engine.ScanFileAsync);
var scanResults = await Task.WhenAll(scanTasks);
return scanResults;
}
示例11: ParseChunk
//.........这里部分代码省略.........
// find all tags
while (!finder.HasReachedEnd)
{
var next = finder.Next();
if (next != null)
tags.Enqueue(next);
}
// return original input if we've no valid bbcode tags
if (tags.All(x => x.Type == BbCodeType.None))
return new[] {AsChunk(input)};
#endregion
#region handle unbalanced tags
var unbalancedTags =
(from t in tags
where t.Type != BbCodeType.None
group t by t.Type
into g
select new {Type = g.Key, Tags = g})
.Where(x => x.Tags.Count()%2 == 1);
foreach (var tagGroup in unbalancedTags.ToList())
tagGroup.Tags.First().Type = BbCodeType.None;
#endregion
while (tags.Count > 0)
{
// get the next tag to process
var tag = tags.Dequeue();
var addToQueue = true;
#region add as child of last tag
// check if we're in the context of another open tag
if (openTags.Count > 0)
{
var lastOpen = openTags.Peek();
// check if we're the closing for the last open tag
if (lastOpen.Type == tag.Type
&& tag.IsClosing)
{
lastOpen.ClosingTag = tag;
openTags.Pop();
#region handle noparse
if (lastOpen.Type == BbCodeType.NoParse)
{
lastOpen.Children = lastOpen.Children ?? new List<BbTag>();
lastOpen.Children.Add(new BbTag
{
Type = BbCodeType.None,
End = tag.Start,
Start = lastOpen.End
});
}
#endregion
}
else
{
if (lastOpen.Type != BbCodeType.NoParse)
{
// if not, we have to be a child of it
lastOpen.Children = lastOpen.Children ?? new List<BbTag>();
lastOpen.Children.Add(tag);
}
addToQueue = false;
}
}
#endregion
// we don't need to continue processing closing tags
if (tag.IsClosing) continue;
// tell the system we're in the context of this tag now
if (tag.Type != BbCodeType.None) // text content can't have children
openTags.Push(tag);
// if we're added as a child to another tag, don't process independently of parent
if (addToQueue) processedQueue.Enqueue(tag);
}
// if in the process of removing improper tags we end up with no bbcode,
// return original
if (processedQueue.All(x => x.Type == BbCodeType.None))
return new[] {AsChunk(input)};
toReturn.AddRange(processedQueue.Select(x => FromTag(x, input)));
return toReturn;
}
示例12: Parse
public bool Parse(string[] args)
{
List<Option> availableOptions = new List<Option>(this.Options);
Queue<Argument> availableArguments = new Queue<Argument>(this.Arguments);
Option option = null;
Argument expected = null;
foreach (string arg in args)
{
// Option
if (arg.StartsWith("-"))
{
option = this.Options.Where(n => n.Name == arg.Substring(1)).FirstOrDefault();
if (option == null)
{
Console.WriteLine("Option " + arg + " not available!");
return false;
}
option.Used = true;
availableOptions.Remove(option);
expected = option.Arguments.FirstOrDefault();
continue;
}
// Option Argument!
if (expected != null)
{
if (!expected.Parse(arg))
{
Console.WriteLine("Invalid Parameter Type for " + option.Name + " at position " + option.Arguments.IndexOf(expected));
return false;
}
expected = option.Arguments.SkipWhile(n => n != expected).FirstOrDefault();
if (expected == null)
{
option = null;
}
continue;
}
if (availableArguments.Count == 0)
{
Console.WriteLine("Invalid Argument " + arg);
return false;
}
Argument cur = availableArguments.Dequeue();
if (!cur.Parse(arg))
{
Console.WriteLine("Invalid Parameter Type for Argument " + cur.Name);
return false;
}
}
if (availableArguments.Count > 0)
{
Console.WriteLine("The arguments " + string.Join(", ", availableArguments.Select(n => n.Name)) + " missing!");
return false;
}
return true;
}
示例13: TarefaMaisCurta
public List<ITarefa> TarefaMaisCurta(List<ITarefa> Tarefas)
{
Queue<ITarefa> filaOrdenada = new Queue<ITarefa>(Tarefas.OrderBy(item => item.TempoDuracao));
ITarefa emExecucao;
do
{
emExecucao = filaOrdenada.Peek();
Thread.Sleep(5000);
emExecucao.TempoDuracao = 0;
Console.WriteLine($"A tarefa {emExecucao.Nome} foi finalizada!");
filaOrdenada.Dequeue();
filaOrdenada.Enqueue(emExecucao);
} while (filaOrdenada.Select(item => item.TempoDuracao).All(item => item == 0));
return new List<ITarefa>(filaOrdenada);
}
示例14: BuildTree
/// <summary>
/// Builds the expression tree from the token queue
/// </summary>
/// <returns></returns>
public Expression BuildTree(Expression scopeParam = null, bool isCall = false)
{
if (_tokenQueue.Count == 0) Parse(scopeParam != null);
// make a copy of the queue, so that we don't empty the original queue
var tempQueue = new Queue<Token>(_tokenQueue);
var exprStack = new Stack<Expression>();
var args = new List<Expression>();
var literalStack = new Stack<String>();
#if DEBUG
var q = tempQueue.Select(x => (x.Value ?? "<null>").ToString() + (x.GetType() == typeof(MemberToken) ? ":" + ((MemberToken)x).Name : ""));
System.Diagnostics.Debug.WriteLine(string.Join("][", q.ToArray()));
#endif
int isCastPending = -1;
Type typeCast = null;
while (tempQueue.Count > 0)
{
Token t = tempQueue.Dequeue();
t.IsCall = isCall && tempQueue.Count == 0;
if (isCastPending > -1) isCastPending--;
if (isCastPending == 0)
{
exprStack.Push(Expression.Convert(exprStack.Pop(), typeCast));
isCastPending = -1;
}
if (t.IsIdent)
{
// handle numeric literals
exprStack.Push(Expression.Constant(t.Value, t.Type));
}
else if (t.IsType)
{
exprStack.Push(Expression.Constant(t.Value));
}
else if (t.IsScope)
{
if (scopeParam == null)
{
throw new Exception(string.Format("Unexpected identifier {0} or scope empty", t.Value));
}
exprStack.Push(scopeParam);
}
else if (t.IsOperator)
{
// handle operators
Expression result = null;
var op = _operators[(string)t.Value];
var opfunc = OpFuncServiceLocator.Resolve(op.GetType());
for (int i = 0; i < t.ArgCount; i++)
{
args.Add(exprStack.Pop());
}
// Arguments are in reverse order
args.Reverse();
result = opfunc(new OpFuncArgs()
{
TempQueue = tempQueue,
ExprStack = exprStack,
T = t,
Op = op,
Args = args,
ScopeParam = scopeParam,
Types = new List<string>() {"System.Linq"}
});
args.Clear();
exprStack.Push(result);
}
else if (t.IsCast)
{
isCastPending = 2;
typeCast = t.Type;
}
}
// we should only have one complete expression on the stack, otherwise, something went wrong
if (exprStack.Count == 1)
{
Expression pop = exprStack.Pop();
#if DEBUG
System.Diagnostics.Debug.WriteLine(pop.ToString());
#endif
return pop;
}
else
{
throw new Exception("Invalid expression");
}
return null;
}
示例15: ParseChunk
//.........这里部分代码省略.........
}
// return original input if we've no valid bbcode tags
if (tags.All(x => x.Type == BbCodeType.None))
return new[] {AsChunk(input)};
#endregion
while (tags.Count > 0)
{
// get the next tag to process
var tag = tags.Dequeue();
var addToQueue = true;
#region add as child of last tag
// check if we're in the context of another open tag
if (openTags.Count > 0)
{
var lastOpen = openTags.Peek();
var lastMatching = openTags.FirstOrDefault(x => tag.IsClosing && x.Type == tag.Type);
// check if we're closing any previous tags
if (lastMatching != null)
{
lastMatching.ClosingTag = tag;
// keep going through our opened tag stack until we find the one
// we're closing
do
{
lastOpen = openTags.Pop();
// if we end up with a tag that isn't the one we're closing,
// it must not have been closed correctly, e.g
// [i] [b] [/i]
// we'll treat that '[b]' as text
if (lastOpen != lastMatching) lastOpen.Type = BbCodeType.None;
} while (lastOpen != lastMatching);
#region handle noparse
if (lastMatching.Type == BbCodeType.NoParse)
{
lastMatching.Children = lastMatching.Children ?? new List<BbTag>();
lastMatching.Children.Add(new BbTag
{
Type = BbCodeType.None,
End = tag.Start,
Start = lastMatching.End
});
}
#endregion
}
else
{
if (openTags.All(x => x.Type != BbCodeType.NoParse))
{
// if not, we have to be a child of it
lastOpen.Children = lastOpen.Children ?? new List<BbTag>();
lastOpen.Children.Add(tag);
}
// any matching closing tags would be caught in the if part of this
// branch, this is an invalid tag, treat as text
if (tag.IsClosing) tag.Type = BbCodeType.None;
addToQueue = false;
}
}
#endregion
// we don't need to continue processing closing tags
if (tag.IsClosing) continue;
// tell the system we're in the context of this tag now
// though ignore children of 'text' and 'hr'
if (tag.Type != BbCodeType.None && tag.Type != BbCodeType.HorizontalRule)
openTags.Push(tag);
// if we're added as a child to another tag, don't process independently of parent
if (addToQueue) processedQueue.Enqueue(tag);
}
// these tags haven't been closed, so treat them as invalid
foreach (var openTag in openTags)
openTag.Type = BbCodeType.None;
// if we have no bbcode present, just return the text as-is
if (processedQueue.All(x => x.Type == BbCodeType.None && x.Children == null))
return new[] {AsChunk(input)};
toReturn.AddRange(processedQueue.Select(x => FromTag(x, input)));
return toReturn;
}