System.Collections.Generic.IEnumerable.ToArray()

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.ToArray() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

25251 Examples 7

19 Source : ScriptUtilities.cs
with Apache License 2.0
from abist-co-ltd

public static void AppendScriptingDefinitions(
            BuildTargetGroup targetGroup,
            string[] symbols)
        {
            if (symbols == null || symbols.Length == 0) { return; }

            List<string> toAdd = new List<string>(symbols);
            List<string> defines = new List<string>(PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup).Split(';'));

            PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defines.Union(toAdd).ToArray()));
        }

19 Source : SpeechInputHandlerInspector.cs
with Apache License 2.0
from abist-co-ltd

private static string[] GetDistinctRegisteredKeywords()
        {
            if (!MixedRealityToolkit.IsInitialized ||
                !MixedRealityToolkit.Instance.HasActiveProfile ||
                !MixedRealityToolkit.Instance.ActiveProfile.IsInputSystemEnabled ||
                MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile == null ||
                MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile.SpeechCommands.Length == 0)
            {
                return null;
            }

            List<string> keywords = new List<string>();
            var speechCommands = MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile.SpeechCommands;
            for (var i = 0; i < speechCommands.Length; i++)
            {
                keywords.Add(speechCommands[i].Keyword);
            }

            return keywords.Distinct().ToArray();
        }

19 Source : HashidsGenerator.cs
with MIT License
from abock

public IEnumerable<string> Generate(IEnumerable<string> args)
        {
            var numberStrings = args.ToArray();
            if (numberStrings.Length > 0)
            {
                yield return GenerateSingle(numberStrings);
                yield break;
            }

            string line;
            while ((line = Console.In.ReadLine()) != null)
            {
                yield return GenerateSingle(spaceRegex
                    .Split(line)
                    .Where(a => !string.IsNullOrEmpty(a))
                    .ToArray());
            }
        }

19 Source : Program.cs
with MIT License
from abock

static int Main(string[] args)
        {
            bool showVersion = false;
            int numberOfIds = 1;

            var firstArg = args.FirstOrDefault();
            if (string.IsNullOrEmpty(firstArg) || firstArg[0] == '-' || firstArg[0] == '/')
            {
                switch (firstArg?.Substring(1).ToLowerInvariant())
                {
                    case "h":
                    case "?":
                    case "help":
                    case "-help":
                        break;
                    default:
                        args = new[] { "v4" }
                            .Concat(args)
                            .ToArray();
                        break;
                }
            }

            var suite = new CommandSet("idgen")
            {
                { "Usage: idgen COMMAND [OPTIONS]+" },
                { "" },
                { $"  idgen v{version}" },
                { $"  https://github.com/abock/idgen"},
                { $"  {copyright}"},
                { "" },
                { "OPTIONS:" },
                { "" },
                {
                    "h|?|help",
                    "Show this help.",
                    v => { }
                },
                {
                    "V|version",
                    "Show the idgen version.",
                    v => showVersion = true
                },
                {
                    "n=",
                    "Generate {NUMBER} of identifiers", v =>
                    {
                        if (!NumberParse.TryParse (v, out numberOfIds) || numberOfIds < 0)
                            throw new Exception (
                                "NUMBER must be a positive integer, or zero, for the -number option.");
                    }
                },
                { "" },
                { "COMMANDS:" },
                { "" }
            };

            var generators = new IIdGenerator[]
            {
                new GuidGenerator.V4 (),
                new GuidGenerator.V5 (),
                new GuidGenerator.V3 (),
                new NanoidGenerator (),
                new HashidsGenerator (),
                new XcodeIdGenerator (),
                new PhoneGenerator ()
            };

            foreach (var generator in generators)
            {
                var hasOptions = generator.Options?.Any(o => !string.IsNullOrEmpty(o.Prototype)) ?? false;

                var usageLine = hasOptions ? "[OPTIONS]+" : null;

                if (!string.IsNullOrEmpty(generator.UsageArguments))
                {
                    if (usageLine != null)
                        usageLine += " ";
                    usageLine += generator.UsageArguments;
                }

                if (usageLine != null)
                    usageLine = " " + usageLine;

                var optionSet = new OptionSet
                {
                    { $"Usage: {suite.Suite} {generator.Command}{usageLine}" },
                };

                if (hasOptions)
                {
                    optionSet.Add("");
                    optionSet.Add("OPTIONS:");
                    optionSet.Add("");

                    foreach (Option option in generator.Options)
                        optionSet.Add(option);
                }

                suite.Add(new Command(generator.Command, generator.CommandDescription)
                {
                    Options = optionSet,
                    Run = commandArgs => RunCommand(generator, commandArgs)
                });
            }

            void RunCommand(IIdGenerator generator, IEnumerable<string> commandArgs)
            {
                if (showVersion)
                {
                    Console.WriteLine(version);
                    return;
                }

                for (int i = 0; i < numberOfIds; i++)
                {
                    foreach (var id in generator.Generate(commandArgs))
                    {
                        if (id != null)
                            Console.WriteLine(id);
                    }
                }
            }

            suite.Add(
                "\n" +
                "NOTE: any argument that expects a number my be specified in decimal, " +
                "binary (0b1001), or hex (0xabcd and ab123h) notation. Numbers may " +
                "also contain digit separators (_ and ,) and arbitrary whitespace.");

            try
            {
                suite.Run(args);
            }
            catch (Exception e)
            {
                Error(e.Message);
                return 2;
            }

            return 0;
        }

19 Source : BuildAssetPackages.cs
with MIT License
from absurd-joy

public static void ExportPackages()
	{
        string[] replacedets = replacedetDatabase.Findreplacedets("t:Object", null).Select(s=>replacedetDatabase.GUIDToreplacedetPath(s)).ToArray();
		replacedets = replacedets.Where(s=>
			s.StartsWith("replacedets/Oculus/Avatar/") ||
			s.StartsWith("replacedets/Oculus/AudioManager/") ||
			s.StartsWith("replacedets/Oculus/LipSync/") ||
			s.StartsWith("replacedets/Oculus/Platform/") ||
			s.StartsWith("replacedets/Oculus/Spatializer/") ||
			s.StartsWith("replacedets/Oculus/VoiceMod/") ||
			s.StartsWith("replacedets/Oculus/VR/") ||
			s.StartsWith("replacedets/Oculus/SampleFramework/")
		).ToArray();
		replacedetDatabase.ExportPackage(replacedets, "OculusIntegration.unitypackage");
	}

19 Source : RealtimeOrthogonalHeatmap3DChart.xaml.cs
with MIT License
from ABTSoftware

private void OnNewData(object sender, EventArgs e)
        {
            _tick++;
            if (_tick == 2)
            {
                _tick = 0;
                _step = _random.Next(0, 11);
            }

            var mreplacedVal = new double[100];

            for (int i = 0; i < 100; i++)
            {
                double y = _step * Math.Sin(((2 * Math.PI) * 0.4) * t) + _random.NextDouble() * 2;
                _yValues[i] = y;
                _tValues[i] = t;
                mreplacedVal[i] = y + 10;                

                t += dt;
            }

            var sortData = mreplacedVal.OrderByDescending(x => x);

            using (_series0.SuspendUpdates())
            using (_series1.SuspendUpdates())
            using (_series2.SuspendUpdates())
            {
                _series0.Append(_tValues, _yValues);
                _series1.PushRow(sortData.ToArray());
                _series2.PushRow(sortData.ToArray());
            }
        }

19 Source : FanChartExampleView.xaml.cs
with MIT License
from ABTSoftware

private void FanChartExampleViewLoaded(object sender, RoutedEventArgs e)
        {
            // Variance data is a 2D table containing actual values and several levels of projected high, low values
            IEnumerable<VarPoint> varianceData = GetVarianceData().ToArray();

            // To render the Fan, we use an XyDataSeries and three band series'
            var actualDataSeries = new XyDataSeries<DateTime, double>();
            var var3DataSeries = new XyyDataSeries<DateTime, double>();
            var var2DataSeries = new XyyDataSeries<DateTime, double>();
            var var1DataSeries = new XyyDataSeries<DateTime, double>();

            // Append data values from the Variance table
            actualDataSeries.Append(varianceData.Select(x => x.Date), varianceData.Select(x => x.Actual));
            var3DataSeries.Append(varianceData.Select(x => x.Date), varianceData.Select(x => x.VarMin), varianceData.Select(x => x.VarMax));
            var2DataSeries.Append(varianceData.Select(x => x.Date), varianceData.Select(x => x.Var1), varianceData.Select(x => x.Var4));
            var1DataSeries.Append(varianceData.Select(x => x.Date), varianceData.Select(x => x.Var2), varianceData.Select(x => x.Var3));

            // replacedign data to renderableseries
			lineSeries.DataSeries = actualDataSeries;
			projectedVar3.DataSeries = var3DataSeries;
			projectedVar2.DataSeries = var2DataSeries;
            projectedVar1.DataSeries = var1DataSeries;

            sciChart.ZoomExtents();
        }

19 Source : FanChartExampleView.xaml.cs
with MIT License
from ABTSoftware

private IEnumerable<VarPoint> GetVarianceData()
        {
            var dates = Enumerable.Range(0, 10).Select(i => new DateTime(2011, 01, 01).AddMonths(i)).ToArray();
            var yValues = new RandomWalkGenerator(seed: 0).GetRandomWalkSeries(10).YData;

            for (int i = 0; i < 10; i++)
            {
                double varMax = double.NaN;
                double var4 = double.NaN;
                double var3 = double.NaN;
                double var2 = double.NaN;
                double var1 = double.NaN;
                double varMin = double.NaN;

                if (i > 4)
                {
                    varMax = yValues[i] + (i - 5) * 0.3;
                    var4 = yValues[i] + (i - 5) * 0.2;
                    var3 = yValues[i] + (i - 5) * 0.1;
                    var2 = yValues[i] - (i - 5) * 0.1;
                    var1 = yValues[i] - (i - 5) * 0.2;
                    varMin = yValues[i] - (i - 5) * 0.3;
                }

                yield return new VarPoint(dates[i], yValues[i], var4, var3, var2, var1, varMin, varMax);
            }
        }

19 Source : BoxPlotExampleView.xaml.cs
with MIT License
from ABTSoftware

private IEnumerable<BoxPoint> GetBoxPlotData(int count)
        {
            var dates = Enumerable.Range(0, count).Select(i => new DateTime(2011, 01, 01).AddMonths(i)).ToArray();
            var medianValues = new RandomWalkGenerator(0).GetRandomWalkSeries(count).YData;

            var random = new Random(0);
            for (int i = 0; i < count; i++)
            {
                double med = medianValues[i];

                double min = med - random.NextDouble();
                double max = med + random.NextDouble();

                double lower = (med - min)*random.NextDouble() + min;
                double upper = (max - med)*random.NextDouble() + med;

                yield return new BoxPoint(dates[i], min, lower, med, upper, max);
            }
        }

19 Source : AnnotatedPointMarker.cs
with MIT License
from ABTSoftware

public override void Draw(IRenderContext2D context, IEnumerable<Point> centers)
        {
            TryCacheResources(context);

            var markerLocations = centers.ToArray();
            var locationIndex = 0;
            var prevValue = 0d;

            for (int i = 0; i < _dataPointMetadata.Count; ++i)
            {
                if (_dataPointMetadata[i] is BudgetPointMetadata metadata)
                {
                    var isGain = metadata.GainLossValue >= prevValue;
                    prevValue = metadata.GainLossValue;

                    if (_dataPointIndexes.Contains(i))
                    {
                        var center = markerLocations[locationIndex];
                        var gainLossValue = metadata.GainLossValue + "$";

                        DrawDiamond(context, center, Width, Height, _strokePen, isGain ? _gainFillBrush : _lossFillBrush);
       
                        _textBlock.Text = gainLossValue;
                        _textBlock.MeasureArrange();

                        var xPos = center.X - _textBlock.DesiredSize.Width / 2;
                        xPos = xPos < 0 ? TextIndent : xPos;

                        var marginalRightPos = context.ViewportSize.Width - _textBlock.DesiredSize.Width - TextIndent;
                        xPos = xPos > marginalRightPos ? marginalRightPos : xPos;

                        var yPos = center.Y;
                        var yOffset = isGain ? -_textBlock.DesiredSize.Height - TextIndent : TextIndent;
                        yPos += yOffset;

                        var textRect = new Rect(xPos, yPos, _textBlock.DesiredSize.Width, _textBlock.DesiredSize.Height);
                        context.DrawText(textRect, Stroke, TextSize, gainLossValue, FontFamily, FontWeight, FontStyle);

                        if (metadata.IsCheckPoint)
                            context.DrawQuad(_strokePen, textRect.TopLeft, textRect.BottomRight);

                        locationIndex++;
                    }
                }
            }
        }

19 Source : SeriesBindingViewModel.cs
with MIT License
from ABTSoftware

private IEnumerable<BoxPoint> GetBoxPlotData()
        {
            var dates = Enumerable.Range(0, PointsCount).Select(i => i).ToArray();
            var medianValues = new RandomWalkGenerator(0).GetRandomWalkSeries(PointsCount).YData;
            var random = new Random(0);

            for (int i = 0; i < PointsCount; i++)
            {
                double med = medianValues[i];
                double min = med - random.NextDouble();
                double max = med + random.NextDouble();
                double lower = (med - min)*random.NextDouble() + min;
                double upper = (max - med)*random.NextDouble() + med;

                yield return new BoxPoint(dates[i], min, lower, med, upper, max);
            }
        }

19 Source : SeriesWithMetadata.xaml.cs
with MIT License
from ABTSoftware

private void OnSeriesWithMetadataLoaded(object sender, RoutedEventArgs e)
        {
            var startDate = new DateTime(1995, 1, 1);

            // Budget data
            var yearsData = Enumerable.Range(0, 18).Select(startDate.AddYears).ToArray();
            var gainLossData = new [] {0, -20.5, -30.06, -70.1, -100.22, 10.34, 30.00, 60.12, 50.1, 70.4, 40.55, 30.76, -50.2, -60.00, -20.01, 50.01, 60.32, 60.44};

            // Metadata
            var executivesData = new [] {"Emerson Irwin", "Reynold Harding", "Carl Carpenter", "Merle Godfrey", "Karl Atterberry"};
            var checkPointIndicies = new []{0, 4, 9, 13, 16};

            var ceo = executivesData[0];
            var budgetMetadata = gainLossData.Select((value, index) =>
            {
                var metadata = new BudgetPointMetadata(value);

                if (checkPointIndicies.Contains(index))
                {
                    metadata.IsCheckPoint = true;

                    var ceoIndex = checkPointIndicies.IndexOf(index);
                    ceo = executivesData[ceoIndex];
                }

                metadata.CEO = ceo;

                return metadata;
            }).ToArray();

            var budgetDataSeries = new XyDataSeries<DateTime, double>();

            budgetDataSeries.Append(yearsData, gainLossData, budgetMetadata);

            lineSeries.DataSeries = budgetDataSeries;

            sciChart.ZoomExtents();
        }

19 Source : ExampleDescriptionFormattingConverter.cs
with MIT License
from ABTSoftware

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (MainWindowViewModel.SearchText.IsNullOrEmpty())
            {
                return string.Empty;
            }

            var description = (string)value;
            var result = string.Empty;

            var terms = MainWindowViewModel.SearchText.Split(' ').Where(word => word != "").Select(x => x.ToLower()).ToArray();

            var lines = description.Split(new[] { ". " }, StringSplitOptions.None).ToArray();

            var sentences = new HashSet<string>();
            foreach (var term in terms)
            {
                var containsTerm = lines.Where(x => x != "" && x.ToLower().Contains(term));
                containsTerm.Take(2).ForEachDo(x => sentences.Add(x));
            }

            if (sentences.Any())
            {
                result = HighlightText(sentences.Select(x => x.Trim()).ToArray(), terms);
            }
            else
            {
                foreach (string sentence in lines.Take(2).Select(x => x.Trim()))
                {
                    result = result + (sentence + ". ");
                }
            }

            return result;
        }

19 Source : ExampleFeaturesFormattingConverter.cs
with MIT License
from ABTSoftware

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (MainWindowViewModel.SearchText.IsNullOrEmpty())
            {
                return string.Empty;
            }
            var lines = ((IEnumerable<Features>)value).Select(x => x.ToString()).ToArray();
            var terms = MainWindowViewModel.SearchText.Split(' ').Where(word => word != "").Select(x => x.ToLower()).ToArray();

            var result = new List<string>();

            for (int i = 0; i < lines.Length; i++)
            {
                result.Add(HighlightTermsBase(lines[i], terms));
            }

            return string.Join(", ", result);
        }

19 Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware

private static string[] GetStopWords(string fileName, char splitter)
        {
            replacedembly replacedembly = typeof (CreateInvertedIndex).replacedembly;

            var names = replacedembly.GetManifestResourceNames();

            var allExampleSourceFiles = names.Where(x => x.Contains(fileName));

            var file = allExampleSourceFiles.FirstOrDefault();

            var result = new string[] {};

            if (file != null)
            {
                using (var s = replacedembly.GetManifestResourceStream(file))
                using (var sr = new StreamReader(s))
                {
                    var readToEnd = sr.ReadToEnd();
                    result = readToEnd.Split(splitter);
                    result = result.Select(x =>
                    {
                        if (x.Contains("\n"))
                            return x.Replace("\n", "");
                        return x;
                    }).ToArray();
                }
            }

            return result;
        }

19 Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware

public static IList<string> GetTerms(string text)
        {
            text = text.ToLower();
            text = new Regex(@"\W").Replace(text, " ");

            var words = text.Split(' ').Where(x => x != "").Where(word => !_stopWords.Contains(word)).ToArray();

            var tokenizer = new NGramTokenizer();
            var terms = words
                .Select(tokenizer.Tokenize)
                .SelectMany(strings => strings.SelectMany(inner => inner))
                .Select(sb => sb.ToString())
                .Where(s => !string.IsNullOrEmpty(s) && s.Length > 1)
                .ToList();

            return terms;
        }

19 Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware

public static void ReadIndexFromFile()
        {
            var location = replacedembly.GetExecutingreplacedembly().Location;

            var index = location.IndexOf(@"\bin", StringComparison.InvariantCulture);

            var filePath = location.Substring(0, index) + InvertedIndexRelativePath;

            string[] lines = File.ReadAllLines(filePath);

            _invertedIndex.Clear();
            foreach (var line in lines)
            {
                var splittedLine = line.Split('|');

                string term = splittedLine[0];
                var postings = splittedLine[1].Split(';');
                var termFrequencies = splittedLine[2].Split(',');
                var invertedDocFrequency = double.Parse(splittedLine[3]);

                var termInfos = new List<TermInfo>();

                for (int i = 0; i < postings.Length; i++)
                {
                    var posting = postings[i];
                    var tf = double.Parse(termFrequencies[i]);

                    var post = posting.Split(':');
                    var termEntries = post[1].Split(',').Select(ushort.Parse).ToArray();
                    
                    termInfos.Add(new TermInfo(new Guid(post[0]), termEntries, (float) tf));
                }

                _invertedIndex[term] = new Posting(termInfos) {InvertedDoreplacedentFrequency = invertedDocFrequency};
            }
        }

19 Source : ExampleSearchProvider.cs
with MIT License
from ABTSoftware

public IEnumerable<ExampleId> Query(string text)
        {
            text = text.ToLower();
            text = new Regex(@"\W").Replace(text, " ");

            var terms = text.Split(' ').ToArray();

            IEnumerable<ExampleId> result = null;
            if (terms.Length > 1)
            {
                result = FreeTextQuery(terms);
            }
            else if (terms.Length == 1)
            {
                result = OneWordQuery(terms);
            }

            return result;
        }

19 Source : AscReader.cs
with MIT License
from ABTSoftware

private static AscData ReadFromStream(StreamReader stream, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
        {
            var result = new AscData
            {
                XValues = new List<float>(),
                YValues = new List<float>(),
                ZValues = new List<float>(),
                ColorValues = new List<Color>(),
                NumberColumns = ReadInt(stream, "ncols"),
                NumberRows = ReadInt(stream, "nrows"),
                XllCorner = ReadInt(stream, "xllcorner"),
                YllCorner = ReadInt(stream, "yllcorner"),
                CellSize = ReadInt(stream, "cellsize"),
                NoDataValue = ReadInt(stream, "NODATA_value"),
            };

            // Load the ASC file format 

            // Generate X-values based off cell position 
            float[] xValuesRow = Enumerable.Range(0, result.NumberColumns).Select(x => (float)x * result.CellSize).ToArray();

            for (int i = 0; i < result.NumberRows; i++)
            {
                // Read heights from the ASC file and generate Z-cell values
                float[] heightValuesRow = ReadFloats(stream, " ", result.NoDataValue);
                float[] zValuesRow = Enumerable.Repeat(0 + i * result.CellSize, result.NumberRows).Select(x => (float)x).ToArray();

                result.XValues.AddRange(xValuesRow);
                result.YValues.AddRange(heightValuesRow);
                result.ZValues.AddRange(zValuesRow);

                if (colorMapFunction != null)
                {
                    // Optional color-mapping of points based on height 
                    Color[] colorValuesRow = heightValuesRow
                        .Select(colorMapFunction)
                        .ToArray();
                    result.ColorValues.AddRange(colorValuesRow);
                }

                // Optional report loading progress 0-100%
                reportProgress?.Invoke((int)(100.0f * i / result.NumberRows));
            }

            return result;
        }

19 Source : AscReader.cs
with MIT License
from ABTSoftware

private static float[] ReadFloats(StreamReader file, string separator, float noDataValue)
        {
            string line = file.ReadLine();
            float[] values = line.Split(new[] {separator}, StringSplitOptions.RemoveEmptyEntries)
                .Select(x =>
                {
                    float rawValue = float.Parse(x, NumberFormatInfo.InvariantInfo);
                    return rawValue.CompareTo(noDataValue) == 0 ? float.NaN : rawValue;
                } ).ToArray();
            return values;
        }

19 Source : SerializationUtil.cs
with MIT License
from ABTSoftware

public static XDoreplacedent Serialize(IEnumerable<ExampleUsage> usages)
        {
            var doc = new XDoreplacedent();

            using (var writer = doc.CreateWriter())
            {
                var serializer = new XmlSerializer(typeof(Item[]), new XmlRootAttribute { ElementName = "items" });

                serializer.Serialize(writer, usages.Select(e => new Item { ExampleName = e.ExampleID, ExampleUsage = e }).ToArray());
            }

            return doc;
        }

19 Source : AscReader.cs
with MIT License
from ABTSoftware

public static async Task<AscData> ReadFileToAscData(
            string filename, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
        {
            AscData result = new AscData()
            {
                XValues = new List<float>(),
                YValues = new List<float>(),
                ZValues = new List<float>(),
                ColorValues = new List<Color>(),
            };

            await Task.Run(() =>
            {
                using (var file = File.OpenText(filename))
                {
                    // Load the ASC file format 
                    result.NumberColumns = ReadInt(file, "ncols");
                    result.NumberRows = ReadInt(file, "nrows");
                    result.XllCorner = ReadInt(file, "xllcorner");
                    result.YllCorner = ReadInt(file, "yllcorner");
                    result.CellSize = ReadInt(file, "cellsize");
                    result.NoDataValue = ReadInt(file, "NODATA_value");

                    // Generate X-values based off cell position 
                    float[] xValuesRow = Enumerable.Range(0, result.NumberColumns).Select(x => (float)x * result.CellSize).ToArray();

                    for (int i = 0; i < result.NumberRows; i++)
                    {
                        // Read heights from the ASC file and generate Z-cell values
                        float[] heightValuesRow = ReadFloats(file, " ", result.NoDataValue);
                        float[] zValuesRow = Enumerable.Repeat(0 + i * result.CellSize, result.NumberRows).Select(x => (float)x).ToArray();

                        result.XValues.AddRange(xValuesRow);
                        result.YValues.AddRange(heightValuesRow);
                        result.ZValues.AddRange(zValuesRow);

                        if (colorMapFunction != null)
                        {
                            // Optional color-mapping of points based on height 
                            Color[] colorValuesRow = heightValuesRow
                                .Select(colorMapFunction)
                                .ToArray();
                            result.ColorValues.AddRange(colorValuesRow);
                        }

                        // Optional report loading progress 0-100%
                        reportProgress?.Invoke((int)(100.0f * i / result.NumberRows));
                    }
                }
            });

            return result;
        }

19 Source : AscReader.cs
with MIT License
from ABTSoftware

private static float[] ReadFloats(StreamReader file, string separator, float noDataValue)
        {
            string line = file.ReadLine();

            float[] values = line.Split(new[] {separator}, StringSplitOptions.RemoveEmptyEntries)
                .Select(x =>
                {
                    float rawValue = float.Parse(x, CultureInfo.InvariantCulture);
                    return rawValue.CompareTo(noDataValue) == 0 ? float.NaN : rawValue;

                } ).ToArray();

            return values;
        }

19 Source : FeatureBuilder.cs
with Apache License 2.0
from acblog

public Feature Build() => new Feature { Items = Inner.ToArray() };

19 Source : KeywordBuilder.cs
with Apache License 2.0
from acblog

public Keyword Build() => new Keyword { Items = Inner.ToArray() };

19 Source : PageRepositoryBuilder.cs
with Apache License 2.0
from acblog

async Task BuildRouteIndex(IList<Page> data)
        {
            var gr = from x in data group x by x.Route;

            foreach (var g in gr)
            {
                string path = Paths.GetRouteFile(RootPath, g.Key);
                await using var st = FSStaticBuilder.GetFileRewriteStream(path);
                await JsonSerializer.SerializeAsync(st, (from p in g select p.Id).ToArray()).ConfigureAwait(false);
            }
        }

19 Source : PostRepositoryBuilder.cs
with Apache License 2.0
from acblog

public override async Task Build(IList<Post> data)
        {
            data = (from x in data orderby x.CreationTime descending select x).ToArray();
            await base.Build(data).ConfigureAwait(false);
            await BuildIndexType(data).ConfigureAwait(false);
            await BuildIndexKeyword(data).ConfigureAwait(false);
            await BuildIndexCategory(data).ConfigureAwait(false);
        }

19 Source : ACBrIBGE.cs
with MIT License
from ACBrNet

private void ProcessarResposta(string resposta)
		{
			try
			{
				Resultados.Clear();

				var buffer = resposta.ToLower();
				var pos = buffer.IndexOf("<div id=\"miolo_interno\">", StringComparison.Ordinal);
				if (pos <= 0) return;

				buffer = buffer.Substring(pos, buffer.Length - pos);
				buffer = buffer.GetStrBetween("<table ", "</table>");

				var rows = Regex.Matches(buffer, @"(?<1><TR[^>]*>\s*<td.*?</tr>)", RegexOptions.Singleline | RegexOptions.IgnoreCase)
								.Cast<Match>()
								.Select(t => t.Value)
								.ToArray();

				if (rows.Length < 2) return;

				for (var i = 1; i < rows.Length; i++)
				{
					var columns = Regex.Matches(rows[i], @"<td[^>](.+?)<\/td>", RegexOptions.Singleline | RegexOptions.IgnoreCase)
									   .Cast<Match>()
									   .Select(t => t.Value.StripHtml().Replace(" ", string.Empty).Trim())
									   .ToArray();

					var municipio = new ACBrMunicipio
					{
						CodigoUF = columns[0].ToInt32(),
						UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), columns[1].ToUpper()),
						Codigo = columns[2].ToInt32(),
						Nome = columns[3].ToreplacedleCase(),
						Area = columns[4].ToDecimal()
					};

					Resultados.Add(municipio);
				}
			}
			catch (Exception exception)
			{
				throw new ACBrException(exception, "Erro ao processar retorno.");
			}
		}

19 Source : GenericInterface.cs
with MIT License
from Accelerider

private TDelegate GetActionWithParams<TDelegate>(string methodName, params Type[] argTypes)
            {
                var methodInfo = Type.GetMethod(methodName) ?? throw new ArgumentException(nameof(methodName));
                var argTypeList = argTypes.Any() ? argTypes : typeof(TDelegate).GetGenericArguments();
                (ParameterExpression expression, Type type)[] argObjectParameters = argTypeList
                    .Select(item => (Expression.Parameter(typeof(object)), item))
                    .ToArray();

                var method = Expression.Lambda<TDelegate>(
                        Expression.Call(
                            Expression.Constant(_instance),
                            methodInfo,
                            argObjectParameters.Select(item => Expression.Convert(item.expression, item.type))),
                        argObjectParameters.Select(item => item.expression))
                    .Compile();

                return method;
            }

19 Source : Guards.cs
with MIT License
from Accelerider

public static void ThrowIfNullOrEmpty(IEnumerable<string> strings)
        {
            ThrowIfNull(strings);
            ThrowIfNullOrEmpty(strings.ToArray());
        }

19 Source : UpgradeService.cs
with MIT License
from Accelerider

private async Task RunInternalAsync(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                bool requiredRetry = false;
                try
                {
                    var tasks = _tasks.Values.ToArray();
                    foreach (var task in tasks)
                    {
                        await task.LoadFromLocalAsync();
                    }

                    var upgradeInfos = await _upgradeInfosGetter();

                    foreach (var task in tasks)
                    {
                        var info = upgradeInfos.FirstOrDefault(
                            item => item.Name.Equals(task.Name, StringComparison.InvariantCultureIgnoreCase));

                        if (info == null) continue;

                        await task.LoadFromRemoteAsync(info);
                    }
                }
                catch (Exception)
                {
                    requiredRetry = true;
                }

                try
                {
                    await Task.Delay(TimeSpan.FromMinutes(requiredRetry
                            ? RetryIntervalBaseMinute
                            : UpgradeIntervalBaseMinute),
                        token);
                }
                catch (TaskCanceledException)
                {
                    // Ignore
                }
            }
        }

19 Source : UpgradeTaskBase.cs
with MIT License
from Accelerider

public virtual Version GetMaxLocalVersion()
        {
            var versions = GetLocalVersions()
                .Select(item => item.Version)
                .ToArray();

            return versions.Any() ? versions.Max() : EmptyVersion;
        }

19 Source : EnumerableExtensions.cs
with MIT License
from Accelerider

public static void ForEach<T>(this IEnumerable<T> @this, Action<T> callback, bool immutable = false)
        {
            Guards.ThrowIfNull(@this, callback);

            var collection = immutable ? @this.ToArray() : @this;

            foreach (T item in collection)
            {
                callback(item);
            }
        }

19 Source : Files.vm.cs
with MIT License
from Accelerider

private async void DownloadCommandExecute(IList files)
        {
            var fileArray = files.Cast<ILazyTreeNode<INetDiskFile>>().ToArray();

            var (to, isDownload) = await DisplayDownloadDialogAsync(fileArray.Select(item => item.Content.Path.FileName));

            if (!isDownload) return;

            var currentFolderPathLength = CurrentFolder.Content.Path.FullPath.Length;
            var fileNames = new List<string>(fileArray.Length);
            foreach (var fileNode in fileArray)
            {
                var targetPath = to;
                var substringStart = currentFolderPathLength;
                if (fileNode.Content.Type == FileType.FolderType)
                {
                    var rootPath = fileNode.Content.Path.FullPath.Substring(substringStart);
                    targetPath = CombinePath(to, rootPath).GetUniqueLocalPath(Directory.Exists);
                    substringStart += rootPath.Length;
                }

                await fileNode.ForEachAsync(file =>
                {
                    if (file.Type == FileType.FolderType) return;

                    var downloadingFile = CurrentNetDiskUser.Download(
                        file,
                        CombinePath(targetPath, file.Path.FolderPath.Substring(substringStart)));
                    downloadingFile.Operations.Ready();
                    // Send this transfer item to the downloading view model.
                    EventAggregator.GetEvent<TransferItemsAddedEvent>().Publish(downloadingFile);
                    fileNames.Add(downloadingFile.File.Path.FileName);
                }, CancellationToken.None);
            }

            if (fileNames.Any())
            {
                var fileName = fileNames.First().TrimMiddle(40);
                var message = fileNames.Count == 1
                    ? string.Format(UiStrings.Message_AddedFileToDownloadList, fileName)
                    : string.Format(UiStrings.Message_AddedFilesToDownloadList, fileName, fileNames.Count);
                GlobalMessageQueue.Enqueue(message);
            }
            else
            {
                GlobalMessageQueue.Enqueue("No Files Found");
            }
        }

19 Source : Files.vm.cs
with MIT License
from Accelerider

private async void DeleteCommandExecute(IList files)
        {
            var currentFolder = CurrentFolder;
            var fileArray = files.Cast<ILazyTreeNode<INetDiskFile>>().ToArray();

            var errorFileCount = 0;
            foreach (var file in fileArray)
            {
                if (!await CurrentNetDiskUser.DeleteFileAsync(file.Content)) errorFileCount++;
            }

            if (errorFileCount < fileArray.Length)
            {
                await RefreshFilesCommand.Execute();
            }

            GlobalMessageQueue.Enqueue($"({fileArray.Length - errorFileCount}/{fileArray.Length}) files have been deleted.");
        }

19 Source : FileDownloaderBuilder.cs
with MIT License
from Accelerider

public IDownloader Build(DownloadContext context, IEnumerable<BlockTransferContext> blockContexts)
        {
            Guards.ThrowIfNull(context);

            if (context.RemotePathProvider == null)
            {
                context.RemotePathProvider = _remotePathProvider ?? throw new ArgumentException("The Context.RemotePathProvider cannot be null");
            }

            context.RemotePathProvider = _remotePathProviderInterceptor(context.RemotePathProvider);

            var blockContextsArray = blockContexts?.ToArray();
            return blockContextsArray != null && blockContextsArray.Any()
                ? InternalBuild(context, ctx => token =>
                {
                    blockContextsArray.ForEach(item =>
                    {
                        item.LocalPath = ctx.LocalPath;
                        item.RemotePathGetter = ctx.RemotePathProvider.GetAsync;
                    });
                    return Task.FromResult(blockContextsArray.AsEnumerable());
                })
                : InternalBuild(context, GetBlockTransferContextGenerator);
        }

19 Source : Wave.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void ReadData(Stream stream)
        {
            var binaryWriter = new BinaryWriter(stream);

            binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("RIFF"));

            uint filesize = (uint)(Data.Length + 36); // 36 is added for all the extra we're adding for the WAV header format
            binaryWriter.Write(filesize);

            binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("WAVE"));

            binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("fmt"));
            binaryWriter.Write((byte)0x20); // Null ending to the fmt

            binaryWriter.Write((int)0x10); // 16 ... length of all the above

            // AC audio headers start at Format Type,
            // and are usually 18 bytes, with some exceptions
            // notably objectID A000393 which is 30 bytes

            // WAV headers are always 16 bytes from Format Type to end of header,
            // so this extra data is truncated here.
            binaryWriter.Write(Header.Take(16).ToArray());

            binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("data"));
            binaryWriter.Write((uint)Data.Length);
            binaryWriter.Write(Data);
        }

19 Source : FileDownloader.cs
with MIT License
from Accelerider

private async Task<IDisposable> Start(CancellationToken cancellationToken)
        {
            var blockContexts = (await _buildInfo.BlockTransferContextGeneratorBuilder(Context).Invoke(cancellationToken)).ToArray();

            _blockTransferContextCache = new ConcurrentDictionary<long, BlockTransferContext>(
                blockContexts.ToDictionary(item => item.Offset));

            return CreateAndRunBlockDownloadItems(blockContexts);
        }

19 Source : AccountExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static string GetPreplacedwordHash(Account account, string preplacedword)
        {
            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(preplacedword);
            byte[] saltBytes = Convert.FromBase64String(account.PreplacedwordSalt);
            byte[] buffer = preplacedwordBytes.Concat(saltBytes).ToArray();
            byte[] hash;

            using (SHA512Managed hasher = new SHA512Managed())
                hash = hasher.ComputeHash(buffer);

            return Convert.ToBase64String(hash);
        }

19 Source : PropertyAttribute2nd.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static string ToSentence(this PropertyAttribute2nd attribute2nd)
        {
            return new string(attribute2nd.ToString().Replace("Max", "Maximum").ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
        }

19 Source : FactionBits.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static string ToSentence(this FactionBits factionBits)
        {
            return new string(factionBits.ToString().ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
        }

19 Source : HookGroupType.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static string ToSentence(this HookGroupType hookGroupType)
        {
            return new string(hookGroupType.ToString().ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
        }

19 Source : Skill.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static string ToSentence(this Skill skill)
        {
            return new string(skill.ToString().ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
        }

19 Source : Player_Spells.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void CreateSentinelBuffPlayers(IEnumerable<Player> players, bool self = false, ulong maxLevel = 8)
        {
            if (!(Session.AccessLevel >= AccessLevel.Sentinel)) return;

            var SelfOrOther = self ? "Self" : "Other";

            // ensure level 8s are installed
            var maxSpellLevel = Math.Clamp(maxLevel, 1, 8);
            if (maxSpellLevel == 8 && DatabaseManager.World.GetCachedSpell((uint)SpellId.ArmorOther8) == null)
                maxSpellLevel = 7;

            var tySpell = typeof(SpellId);
            List<BuffMessage> buffMessages = new List<BuffMessage>();
            // prepare messages
            List<string> buffsNotImplementedYet = new List<string>();
            foreach (var spell in Buffs)
            {
                var spellNamPrefix = spell;
                bool isBane = false;
                if (spellNamPrefix.StartsWith("@"))
                {
                    isBane = true;
                    spellNamPrefix = spellNamPrefix.Substring(1);
                }
                string fullSpellEnumName = spellNamPrefix + ((isBane) ? string.Empty : SelfOrOther) + maxSpellLevel;
                string fullSpellEnumNameAlt = spellNamPrefix + ((isBane) ? string.Empty : ((SelfOrOther == "Self") ? "Other" : "Self")) + maxSpellLevel;
                uint spellID = (uint)Enum.Parse(tySpell, fullSpellEnumName);
                var buffMsg = BuildBuffMessage(spellID);

                if (buffMsg == null)
                {
                    spellID = (uint)Enum.Parse(tySpell, fullSpellEnumNameAlt);
                    buffMsg = BuildBuffMessage(spellID);
                }

                if (buffMsg != null)
                {
                    buffMsg.Bane = isBane;
                    buffMessages.Add(buffMsg);
                }
                else
                {
                    buffsNotImplementedYet.Add(fullSpellEnumName);
                }
            }
            // buff each player
            players.ToList().ForEach(targetPlayer =>
            {
                if (buffMessages.Any(k => !k.Bane))
                {
                    // bake player into the messages
                    buffMessages.Where(k => !k.Bane).ToList().ForEach(k => k.SetTargetPlayer(targetPlayer));
                    // update client-side enchantments
                    targetPlayer.Session.Network.EnqueueSend(buffMessages.Where(k => !k.Bane).Select(k => k.SessionMessage).ToArray());
                    // run client-side effect scripts, omitting duplicates
                    targetPlayer.EnqueueBroadcast(buffMessages.Where(k => !k.Bane).ToList().GroupBy(m => m.Spell.TargetEffect).Select(a => a.First().LandblockMessage).ToArray());
                    // update server-side enchantments

                    var buffsForPlayer = buffMessages.Where(k => !k.Bane).ToList().Select(k => k.Enchantment);

                    var lifeBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.LifeMagic).ToList();
                    var critterBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.CreatureEnchantment).ToList();
                    var itemBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.ItemEnchantment).ToList();

                    lifeBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                    critterBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                    itemBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                }
                if (buffMessages.Any(k => k.Bane))
                {
                    // Impen/bane
                    var items = targetPlayer.EquippedObjects.Values.ToList();
                    var itembuffs = buffMessages.Where(k => k.Bane).ToList();
                    foreach (var itemBuff in itembuffs)
                    {
                        foreach (var item in items)
                        {
                            if ((item.WeenieType == WeenieType.Clothing || item.IsShield) && item.IsEnchantable)
                                CreateEnchantmentSilent(itemBuff.Spell, item);
                        }
                    }
                }
            });
        }

19 Source : Diagnostics.cs
with MIT License
from acidbubbles

internal static string GetList(IEnumerable<string> values)
    {
        return string.Join(", ", values.ToArray());
    }

19 Source : CmdLineActions.cs
with MIT License
from action-bi-toolkit

[ArgActionMethod, ArgShortcut("cache"), ArgDescription("Manages the internal replacedembly cache.")]
        [ArgExample("pbi-tools.exe cache list", "Lists all cache folders present in the current user profile.")]
        public void Cache(
            [ArgRequired, ArgDescription("The cache action to perform.")] CacheAction action
        )
        {
            var folders = Directory.GetDirectories(ApplicationFolders.AppDataFolder);
            
            switch (action)
            {
                case CacheAction.List:
                    Array.ForEach(folders, f =>
                        Console.WriteLine($"- {Path.GetFileName(f)}")
                    );
                    break;
                case CacheAction.ClearAll:
                    Array.ForEach(folders, f => 
                    {
                        Directory.Delete(f, recursive: true);
                        Console.WriteLine($"Deleted: {Path.GetFileName(f)}");
                    });
                    break;
                case CacheAction.ClearOutdated:
                    Array.ForEach(folders.OrderByDescending(x => x).Skip(1).ToArray(), f => 
                    {
                        Directory.Delete(f, recursive: true);
                        Console.WriteLine($"Deleted: {Path.GetFileName(f)}");
                    });
                    break;
            }
        }

19 Source : ProjectRootFolder.cs
with MIT License
from action-bi-toolkit

public void Dispose()
        {
            // Do not delete anything if an unhandled error has occurred
            if (!_committed) return;

            if (_filesWritten.Count == 0)
            {
                if (Directory.Exists(BasePath))
                {
                    Directory.Delete(BasePath, recursive: true);
                    Log.Information("No files written. Removed base folder: {Path}", BasePath);
                }

                return;
            }

            // Remove any existing files that have not been updated
            foreach (var path in Directory.GetFiles(BasePath, "*.*", SearchOption.AllDirectories))
            {
                if (!_filesWritten.Contains(path))
                {
                    File.Delete(path);
                    Log.Information("Removed file: {Path}", path);
                }
            }

            // Remove empty dirs:
            foreach (var dir in Directory.GetDirectories(BasePath, "*", SearchOption.AllDirectories).ToArray())
            {
                if (Directory.Exists(dir) && Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories).FirstOrDefault() == null)
                {
                    Directory.Delete(dir, recursive: true); // Could be root of a series of empty folders
                    Log.Information("Removed empty directory: {Path}", dir);
                }
            }

            // TODO Check if nested empty dirs need to be removed explicitly
            // ./ROOT
            // ./ROOT/dir1
            // ./ROOT/dir1/file.txt
            // ./ROOT/dir1/empty/ ***
        }

19 Source : HostContext.cs
with MIT License
from actions

protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            if (eventData == null)
            {
                return;
            }

            string message = eventData.Message;
            object[] payload = new object[0];
            if (eventData.Payload != null && eventData.Payload.Count > 0)
            {
                payload = eventData.Payload.ToArray();
            }

            try
            {
                if (_vssHttpMethodEventIds.Contains(eventData.EventId))
                {
                    payload[0] = Enum.Parse(typeof(VssHttpMethod), ((int)payload[0]).ToString());
                }
                else if (_vssHttpCredentialEventIds.Contains(eventData.EventId))
                {
                    payload[0] = Enum.Parse(typeof(GitHub.Services.Common.VssCredentialsType), ((int)payload[0]).ToString());
                }

                if (payload.Length > 0)
                {
                    message = String.Format(eventData.Message.Replace("%n", Environment.NewLine), payload);
                }

                switch (eventData.Level)
                {
                    case EventLevel.Critical:
                    case EventLevel.Error:
                        _actionsHttpTrace.Error(message);
                        break;
                    case EventLevel.Warning:
                        _actionsHttpTrace.Warning(message);
                        break;
                    case EventLevel.Informational:
                        _actionsHttpTrace.Info(message);
                        break;
                    default:
                        _actionsHttpTrace.Verbose(message);
                        break;
                }
            }
            catch (Exception ex)
            {
                _actionsHttpTrace.Error(ex);
                _actionsHttpTrace.Info(eventData.Message);
                _actionsHttpTrace.Info(string.Join(", ", eventData.Payload?.ToArray() ?? new string[0]));
            }
        }

19 Source : TabularDataReader.cs
with MIT License
from action-bi-toolkit

public string[] GetTableNames()
        {
            return ExecuteQuery(
                @"select * from $SYSTEM.TMSCHEMA_TABLES", 
                r => r.GetString(r.GetOrdinal("Name"))
            )
            .ToArray(/*Ensures reader is closed*/);
        }

19 Source : SystemUtility.cs
with MIT License
from action-bi-toolkit

public static IEnumerable<FileHandle> GetHandles(int[] processIds)
        {
            var longProcIds = processIds.Select(Convert.ToUInt64).OrderBy(x => x).ToArray();
            uint length = 0x10000;
            IntPtr ptr = IntPtr.Zero;
            try
            {
                try { }
                finally
                {
                    ptr = Marshal.AllocHGlobal((int)length);
                }


                uint returnLength;
                NTSTATUS result;
                while ((result = NativeMethods.NtQuerySystemInformation(
                    SYSTEM_INFORMATION_CLreplaced.SystemHandleInformation, ptr, length, out returnLength)) ==
                       NTSTATUS.STATUS_INFO_LENGTH_MISMATCH)
                {
                    length = ((returnLength + 0xffff) & ~(uint)0xffff);
                    try { }
                    finally
                    {
                        Marshal.FreeHGlobal(ptr);
                        ptr = Marshal.AllocHGlobal((int)length);
                    }
                }

                if (result != NTSTATUS.STATUS_SUCCESS)
                    yield break;

                long handleCount = Marshal.ReadInt64(ptr);
                int offset = sizeof(long) + sizeof(long);
                int size = Marshal.SizeOf(typeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX));
                for (int i = 0; i < handleCount; i++)
                {
                    var handleEntry =
                        (SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX)Marshal.PtrToStructure(
                        IntPtr.Add(ptr, offset), typeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX));

                    if (Array.BinarySearch(longProcIds, handleEntry.UniqueProcessId) > -1 
                        && FileHandle.TryCreate(handleEntry.UniqueProcessId, handleEntry.HandleValue, handleEntry.ObjectTypeIndex, out var fileHandle))
                    {
                        yield return fileHandle;
                    }

                    offset += size;
                }
            }
            finally
            {
                if (ptr != IntPtr.Zero)
                    Marshal.FreeHGlobal(ptr);
            }
        }

See More Examples