System.Collections.Generic.List.Reverse()

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

1050 Examples 7

19 Source : TreeNodeExtensions.cs
with Apache License 2.0
from crazyants

public static List<TreeNode<NavigationNode>> GetParentNodeChain(
            this TreeNode<NavigationNode> currentNode, 
            bool includeCurrentNode,
            bool includeRoot)
        {
            List<TreeNode<NavigationNode>> list = new List<TreeNode<NavigationNode>>();
            if(includeCurrentNode)
            {
                list.Add(currentNode);
            }

            TreeNode<NavigationNode> parentNode = currentNode.Parent;
            while(parentNode != null)
            {
                if(includeRoot ||(!parentNode.Value.IsRootNode))
                {
                    list.Add(parentNode);
                }
               
                parentNode = parentNode.Parent;
            }

            // this is used for breadcrumbs
            // so we want the sort from parent down to current node
            list.Reverse();

            return list;
        }

19 Source : CollectionCopyHint.cs
with Mozilla Public License 2.0
from CreateAndFake

private static object[] CopyContentsHelper(IEnumerable source, DuplicatorChainer duplicator, bool reverse)
        {
            List<object> copy = new();

            IEnumerator enumerator = source.GetEnumerator();
            while (enumerator.MoveNext())
            {
                copy.Add(duplicator.Copy(enumerator.Current));
            }

            if (reverse)
            {
                copy.Reverse();
            }

            return copy.ToArray();
        }

19 Source : QueryTests.cs
with MIT License
from crookookoo

[Test]
    public void ReverseTest([ValueSource("list0")] QueryArg arg) {
      var expected = arg.ToList();
      expected.Reverse();

      replacedert.That(arg.ToQuery().Reverse().ToList(), Is.EquivalentTo(
                  expected));
    }

19 Source : QueryTests.cs
with MIT License
from crookookoo

[Test]
    public void SortDescendingTests([ValueSource("list0")] QueryArg arg) {
      var expected = arg.ToList();
      expected.Sort();
      expected.Reverse();

      replacedert.That(arg.ToQuery().SortDescending().ToList(), Is.EquivalentTo(
                  expected));
    }

19 Source : EasyLayoutBaseType.cs
with MIT License
from cschladetsch

protected static void ReverseList(List<LayoutElementInfo> list)
		{
			list.Reverse();
		}

19 Source : EasyLayoutEllipse.cs
with MIT License
from cschladetsch

protected override void Group()
		{
			EllipseGroup.Clear();
			EllipseGroup.AddRange(Elements);

			if (Layout.RightToLeft)
			{
				EllipseGroup.Reverse();
			}
		}

19 Source : PathArray.cs
with MIT License
from cschladetsch

public virtual void CalculatePath()
        {
            maxPathLength = 0;
            for (int i = 1; i < path.Count; i++)
            {
                maxPathLength += (path[i] - path[i - 1]).magnitude;
            }
            if (counterClockwise)
            {
                path.Reverse();
            }
        }

19 Source : FileListViewPath.cs
with MIT License
from cschladetsch

protected virtual void SetPath(string newPath)
		{
			path = newPath;

			CurrentDirectories.Clear();
			do
			{
				CurrentDirectories.Add(newPath);
				newPath = System.IO.Path.GetDirectoryName(newPath);
			}
			while (!string.IsNullOrEmpty(newPath));
			CurrentDirectories.Reverse();

			for (int i = Components.Count - 1; i >= CurrentDirectories.Count; i--)
			{
				var c = Components[i];
				Components.RemoveAt(i);
				c.Owner = null;
				c.Free();
			}

			for (int i = Components.Count; i < CurrentDirectories.Count; i++)
			{
				Components.Add(Template.Instance());
			}

			CurrentDirectories.ForEach((x, i) =>
			{
				Components[i].Owner = this;
				Components[i].SetPath(x);
			});
		}

19 Source : ObservableList.cs
with MIT License
from cschladetsch

public void Reverse()
		{
			Items.Reverse();

			CollectionChanged();
		}

19 Source : EditorAssetManager.cs
with MIT License
from csinkers

void Apply(IEditorEvent e)
        {
            if (e is EditorAggregateChangeEvent aggregate)
            {
                var applied = new List<IEditorEvent>();
                bool success = true;
                foreach (var subEvent in aggregate.Events)
                {
                    success &= InnerApply(subEvent);
                    if (success)
                        applied.Add(subEvent);
                    else break;
                }

                if (!success)
                {
                    applied.Reverse();
                    foreach (var subEvent in applied)
                        Undo(subEvent);
                    return;
                }
            }
            else
            {
                if (!InnerApply(e))
                    return;
            }

            _undoStack.AddLast(e);
            if (_undoStack.Count > MaxUndo)
                _undoStack.RemoveFirst();
        }

19 Source : ModApplier.cs
with MIT License
from csinkers

public void LoadMods(IGeneralConfig config, IList<string> mods)
        {
            if (config == null) throw new ArgumentNullException(nameof(config));
            if (mods == null) throw new ArgumentNullException(nameof(mods));

            _mods.Clear();
            _modsInReverseDependencyOrder.Clear();
            replacedetMapping.Global.Clear();

            foreach (var mod in mods)
                LoadMod(config.ResolvePath("$(MODS)"), mod);

            _modsInReverseDependencyOrder.Reverse();
            Raise(ModsLoadedEvent.Instance);
        }

19 Source : TreeDataService.cs
with MIT License
from ctrl-alt-d

public async Task<TreeNode[]> GetNodesToAsync(int Id)
        {

            List<TreeNode> aux_nodes = new List<TreeNode>();
            TreeNode auxNode = new TreeNode();
            auxNode.ParentId = Id;
            do
            {
                auxNode = await GetNodeAsync(auxNode.ParentId.Value);
                if (auxNode != null)
                {
                    aux_nodes.Add(auxNode);
                }
            } while (auxNode != null && auxNode.ParentId != null);
            aux_nodes.Reverse();
            return aux_nodes.ToArray();
        }

19 Source : GUIScaleUtility.cs
with MIT License
from Cushmily

public static void BeginNoClip()
        {
            // Record and close all clips one by one, from bottom to top, until we hit the 'origin'
            List<Rect> rectStackGroup = new List<Rect>();
            Rect topMostClip = getTopRect;
            while (topMostClip != new Rect(-10000, -10000, 40000, 40000))
            {
                rectStackGroup.Add(topMostClip);
                GUI.EndClip();
                topMostClip = getTopRect;
            }

            // Store the clips appropriately
            rectStackGroup.Reverse();
            rectStackGroups.Add(rectStackGroup);
            currentRectStack.AddRange(rectStackGroup);
        }

19 Source : GUIScaleUtility.cs
with MIT License
from Cushmily

public static void MoveClipsUp(int count)
        {
            // Record and close all clips one by one, from bottom to top, until reached the count or hit the 'origin'
            List<Rect> rectStackGroup = new List<Rect>();
            Rect topMostClip = getTopRect;
            while (topMostClip != new Rect(-10000, -10000, 40000, 40000) && count > 0)
            {
                rectStackGroup.Add(topMostClip);
                GUI.EndClip();
                topMostClip = getTopRect;
                count--;
            }

            // Store the clips appropriately
            rectStackGroup.Reverse();
            rectStackGroups.Add(rectStackGroup);
            currentRectStack.AddRange(rectStackGroup);
        }

19 Source : Solution.cs
with MIT License
from cwetanow

public static void ReversePartial(this List<int> list, int i, int j)
		{
			var copy = list.GetRange(i, j - i + 1);
			copy.Reverse();

			for (int k = i; k <= j; k++)
			{
				list[k] = copy[k - i];
			}
		}

19 Source : Tests.cs
with MIT License
from cwetanow

[Test]
		public void TestSortListWithReverse_ShouldReturnCorrectly()
		{
			// Arrange
			var list = Enumerable.Range(0, 10).ToList();

			var expectedResult = new List<int>(list);
			list.Reverse();

			// Act
			list.SortListWithReverse();

			// replacedert
			list.Should().BeEquivalentTo(expectedResult).And.BeInAscendingOrder();
		}

19 Source : Solution.cs
with MIT License
from cwetanow

private static void TraverseBoustrophedon(List<int> values, bool fromLeft = true)
		{
			var level = 1;
			while (level <= levels.Max(l => l.Key))
			{
				var toAdd = levels[level].Select(c => c.Value).ToList();

				if (!fromLeft)
				{
					toAdd.Reverse();
				}

				values.AddRange(toAdd);

				level++;
				fromLeft = !fromLeft;
			}
		}

19 Source : ReverseTests.cs
with MIT License
from cwetanow

[Test]
		public void TestReverse_ShouldWorkCorrectly()
		{
			// Arrange
			var linkedList = new Solutions.Common.LinkedList<int>();
			var list = new List<int>();

			for (int i = 0; i < 10; i++)
			{
				linkedList.Add(i);
				list.Add(i);
			}

			list.Reverse();

			// Act 
			linkedList.Reverse();

			// replacedert
			Collectionreplacedert.AreEqual(list, linkedList.ToList());
		}

19 Source : Triangulator.cs
with GNU General Public License v3.0
from CWolfs

public int[] Triangulate() {
        List<int> indices = new List<int>();
 
        int n = m_points.Count;
        if (n < 3)
            return indices.ToArray();
 
        int[] V = new int[n];
        if (Area() > 0) {
            for (int v = 0; v < n; v++)
                V[v] = v;
        }
        else {
            for (int v = 0; v < n; v++)
                V[v] = (n - 1) - v;
        }
 
        int nv = n;
        int count = 2 * nv;
        for (int v = nv - 1; nv > 2; ) {
            if ((count--) <= 0)
                return indices.ToArray();
 
            int u = v;
            if (nv <= u)
                u = 0;
            v = u + 1;
            if (nv <= v)
                v = 0;
            int w = v + 1;
            if (nv <= w)
                w = 0;
 
            if (Snip(u, v, w, nv, V)) {
                int a, b, c, s, t;
                a = V[u];
                b = V[v];
                c = V[w];
                indices.Add(a);
                indices.Add(b);
                indices.Add(c);
                for (s = v, t = v + 1; t < nv; s++, t++)
                    V[s] = V[t];
                nv--;
                count = 2 * nv;
            }
        }
 
        indices.Reverse();
        return indices.ToArray();
    }

19 Source : UnitAI.cs
with GNU General Public License v3.0
from CypherCore

public List<Unit> SelectTargetList(uint num, SelectAggroTarget targetType, uint offset, ICheck<Unit> selector)
        {
            var targetList = new List<Unit>();

            ThreatManager mgr = GetThreatManager();
            // shortcut: we're gonna ignore the first <offset> elements, and there's at most <offset> elements, so we ignore them all - nothing to do here
            if (mgr.GetThreatListSize() <= offset)
                return targetList;

            if (targetType == SelectAggroTarget.MaxDistance || targetType == SelectAggroTarget.MinDistance)
            {
                foreach (ThreatReference refe in mgr.GetSortedThreatList())
                {
                    if (!refe.IsOnline())
                        continue;

                    targetList.Add(refe.GetVictim());
                }
            }
            else
            {
                Unit currentVictim = mgr.GetCurrentVictim();
                if (currentVictim != null)
                    targetList.Add(currentVictim);

                foreach (ThreatReference refe in mgr.GetSortedThreatList())
                {
                    if (!refe.IsOnline())
                        continue;

                    Unit thisTarget = refe.GetVictim();
                    if (thisTarget != currentVictim)
                        targetList.Add(thisTarget);
                }
            }

            // shortcut: the list isn't gonna get any larger
            if (targetList.Count <= offset)
            {
                targetList.Clear();
                return targetList;
            }

            // right now, list is unsorted for DISTANCE types - re-sort by MAXDISTANCE
            if (targetType == SelectAggroTarget.MaxDistance || targetType == SelectAggroTarget.MinDistance)
                SortByDistance(targetList, targetType == SelectAggroTarget.MinDistance);

            // now the list is MAX sorted, reverse for MIN types
            if (targetType == SelectAggroTarget.MinThreat)
                targetList.Reverse();

            // ignore the first <offset> elements
            while (offset != 0)
            {
                targetList.RemoveAt(0);
                --offset;
            }

            // then finally filter by predicate
            targetList.RemoveAll(unit => !selector.Invoke(unit));

            if (targetList.Count <= num)
                return targetList;

            if (targetType == SelectAggroTarget.Random)
                targetList = targetList.SelectRandom(num).ToList();
            else
                targetList.Resize(num);

            return targetList;
        }

19 Source : SoftMaskableEditor.cs
with GNU General Public License v3.0
from Cytoid

void DrawMaskInteractions()
		{
			(target as SoftMaskable).GetComponentsInParent<Mask>(true, tmpMasks);
			tmpMasks.RemoveAll(x => !x.enabled);
			tmpMasks.Reverse();

			maskInteraction = (MaskInteraction)EditorGUILayout.EnumPopup("Mask Interaction", maskInteraction);
			if (_custom)
			{
				var l = EditorGUIUtility.labelWidth;
				EditorGUIUtility.labelWidth = 45;

				using (var ccs = new EditorGUI.ChangeCheckScope())
				{
					int intr0 = DrawMaskInteraction(0);
					int intr1 = DrawMaskInteraction(1);
					int intr2 = DrawMaskInteraction(2);
					int intr3 = DrawMaskInteraction(3);

					if (ccs.changed) {
						_spMaskInteraction.intValue = (intr0 << 0) + (intr1 << 2) + (intr2 << 4) + (intr3 << 6);
					}
				}

				EditorGUIUtility.labelWidth = l;
			}
		}

19 Source : ObjectTableStorage.cs
with GNU Lesser General Public License v3.0
from czsgeo

public void ReverseRows() { this.BufferedValues.Reverse(); }

19 Source : ListUtil.cs
with GNU Lesser General Public License v3.0
from czsgeo

public static void RemoveAt<T>(List<T> values, List<int> tobeRemoves)
        {
            if(tobeRemoves.Count == 0) { return; }

            tobeRemoves.Sort();
            tobeRemoves.Reverse();//����ɾ��
            foreach (var item in tobeRemoves)
            {
                values.RemoveAt(item);
            }
        }

19 Source : LicenseInitializer.cs
with GNU General Public License v3.0
from dahai202

private bool Initialize()
        {
            if (m_requestedProducts == null || m_requestedProducts.Count == 0)
                return false;

            esriLicenseProductCode currentProduct = new esriLicenseProductCode();
            bool productInitialized = false;

            //Try to initialize a product
            ILicenseInformation licInfo = (ILicenseInformation)m_AoInit;

            m_requestedProducts.Sort();
            if (!InitializeLowerProductFirst) //Request license from highest to lowest
                m_requestedProducts.Reverse();

            foreach (int prodNumber in m_requestedProducts)
            {
                esriLicenseProductCode prod = (esriLicenseProductCode)Enum.ToObject(typeof(esriLicenseProductCode), prodNumber);
                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop);

                //esriLicenseStatus status = m_AoInit.IsProductCodeAvailable(prod);
                //if (status == esriLicenseStatus.esriLicenseAvailable)
                //{
                //    status = m_AoInit.Initialize(prod);
                //    if (status == esriLicenseStatus.esriLicenseAlreadyInitialized ||
                //        status == esriLicenseStatus.esriLicenseCheckedOut)
                //    {
                //        productInitialized = true;
                //        currentProduct = m_AoInit.InitializedProduct();
                //    }
                //}

                //m_productStatus.Add(prod, status);

                if (productInitialized)
                    break;
            }

            m_hasInitializeProduct = productInitialized;
            m_requestedProducts.Clear();

            //No product is initialized after trying all requested licenses, quit
            if (!productInitialized)
            {
                return false;
            }

            //Check out extension licenses
            return CheckOutLicenses(currentProduct);
        }

19 Source : ModuleDependencySolver.cs
with Mozilla Public License 2.0
from daixin10310

public string[] Solve()
        {
            List<string> skip = new List<string>();
            while (skip.Count < dependencyMatrix.Count)
            {
                List<string> leaves = this.FindLeaves(skip);
                if (leaves.Count == 0 && skip.Count < dependencyMatrix.Count)
                {
                    throw new CyclicDependencyFoundException("CyclicDependencyFound");
                }
                skip.AddRange(leaves);
            }
            skip.Reverse();

            if (skip.Count > knownModules.Count)
            {
                string moduleNames = this.FindMissingModules(skip);
                throw new ModularityException(moduleNames, string.Format(CultureInfo.CurrentCulture,
                                                            "DependencyOnMissingModule",
                                                            moduleNames));
            }

            return skip.ToArray();
        }

19 Source : Site.cs
with MIT License
from damarindra

internal List<Vector2> Region (Rect clippingBounds)
		{
			if (_edges == null || _edges.Count == 0) {
				return new List<Vector2> ();
			}
			if (_edgeOrientations == null) { 
				ReorderEdges ();
				_region = ClipToBounds (clippingBounds);
				if ((new Polygon (_region)).Winding () == Winding.CLOCKWISE) {
					_region.Reverse ();
				}
			}
			return _region;
		}

19 Source : FrameNewMedia.cs
with The Unlicense
from dantheman213

private void ingestMediaUrl()
        {
            var f = new FrameCheckMetadata();
            try
            {
                string url = textUrl.Text.Trim();
                if (url != lastValidUrl && Common.isValidURL(url))
                {
                    lastValidUrl = url;

                    this.Enabled = false;
                    f.Show();
                    Application.DoEvents();

                    var info = YouTubeDL.getMediaData(url);
                    string thumbnailFilePath = YouTubeDL.downloadThumbnail(info.thumbnail);
                    pbPreview.ImageLocation = thumbnailFilePath;

                    labelreplacedle.Text = info.replacedle;
                    labelDescription.Text = info.description;
                    // TODO: may need to be revised now that using --restrict-filenames flag in youtube-dl
                    textLocation.Text = FrameMain.settings.defaultDownloadPath + "\\" + String.Format("{0}{1}", Common.stripIllegalFileNameChars(info.filename.Substring(0, info.filename.LastIndexOf('.'))), info.filename.Substring(info.filename.LastIndexOf('.')));

                    if (info.formats != null && info.formats.Count > 0)
                    {
                        cbVideoFormat.Items.Clear();
                        cbAudioFormat.Items.Clear();

                        if (info.requestedFormats != null && info.requestedFormats.Count > 0)
                        {
                            info.formats.Insert(0, info.requestedFormats[0]);

                            if (info.requestedFormats.Count > 1)
                            {
                                info.formats.Insert(0, info.requestedFormats[1]);
                            }
                        }

                        string recommendedVideoFormat = "";
                        string recommendedAudioFormat = "";
                        var videoFormatList = new List<string>();
                        var audioFormatList = new List<string>();
                        videoIdLookupTable = new Dictionary<string, string>();
                        audioIdLookupTable = new Dictionary<string, string>();

                        foreach (var format in info.formats)
                        {
                            if (!String.IsNullOrEmpty(format.width) && !String.IsNullOrEmpty(format.height))
                            {
                                string codec = ((!String.IsNullOrEmpty(format.vcodec) && format.vcodec != "none") ? format.vcodec : "unknwon codec");
                                string tbr = ((!String.IsNullOrEmpty(format.tbr)) ? Math.Floor(Convert.ToDecimal(format.tbr)).ToString() + "k" : "---"); // rounds down
                                string fps = ((!String.IsNullOrEmpty(format.fps)) ? format.fps + "fps" : "---");
                                string note = ((!String.IsNullOrEmpty(format.formateNote)) ? format.formateNote : "---");
                                string str = String.Format("{0} x {1} / {2} / {3} / {4} / {5} {6}", format.width.PadRight(4), format.height.PadLeft(4), tbr.PadRight(7), format.ext.PadRight(5), note.PadRight(6), fps.PadLeft(6), codec);

                                if (info.requestedFormats != null && String.IsNullOrEmpty(recommendedVideoFormat))
                                {
                                    str += " [Recommended]";
                                    recommendedVideoFormat = str;
                                }
                                else
                                {
                                    videoFormatList.Add(str);
                                }

                                if (!videoIdLookupTable.ContainsKey(str))
                                {
                                    videoIdLookupTable.Add(str, format.formatId);
                                }
                            }

                            if (!String.IsNullOrEmpty(format.acodec) && format.acodec != "none")
                            {
                                var bitrate = (String.IsNullOrEmpty(format.abr) ? "---" : format.abr + " kbps");
                                var sampleRate = (String.IsNullOrEmpty(format.asr) ? "---" : format.asr + "Hz");
                                var str = String.Format("{0} / {1} / {2} / {3}", bitrate.PadRight(9), sampleRate.PadLeft(8), format.ext.PadRight(5), format.acodec);

                                if (info.requestedFormats != null && String.IsNullOrEmpty(recommendedAudioFormat))
                                {
                                    str += " [Recommended]";
                                    recommendedAudioFormat = str;
                                }
                                else
                                {
                                    audioFormatList.Add(str);
                                }

                                if (!audioIdLookupTable.ContainsKey(str))
                                {
                                    audioIdLookupTable.Add(str, format.formatId);
                                }
                            }
                        }

                        if (!String.IsNullOrEmpty(recommendedVideoFormat))
                        {
                            cbVideoFormat.Items.Add(recommendedVideoFormat);
                        }

                        try
                        {
                            videoFormatList.Sort((x, y) => Int32.Parse(x.Trim().Split(' ')[0]).CompareTo(Int32.Parse(y.Trim().Split(' ')[0])));
                        }
                        catch (FormatException ex)
                        {
                            Console.WriteLine(ex);
                        }
                        videoFormatList.Reverse(); // TODO: optimze this out
                        foreach (var item in videoFormatList)
                        {
                            cbVideoFormat.Items.Add(item);
                        }

                        if (!String.IsNullOrEmpty(recommendedAudioFormat))
                        {
                            cbAudioFormat.Items.Add(recommendedAudioFormat);
                        }

                        try
                        {
                            audioFormatList.Sort((x, y) => Int32.Parse(x.Trim().Split(' ')[0]).CompareTo(Int32.Parse(y.Trim().Split(' ')[0])));
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }

                        audioFormatList.Reverse(); // TODO: optimze this out
                        foreach (var item in audioFormatList)
                        {
                            cbAudioFormat.Items.Add(item);
                        }

                        if (cbVideoFormat.Items.Count < 1)
                        {
                            cbVideoFormat.Items.Add("(no video metadata could be extracted)");
                        }
                        cbVideoFormat.SelectedIndex = 0;
                        if (cbAudioFormat.Items.Count < 1)
                        {
                            cbAudioFormat.Items.Add("(no audio metadata could be extracted)");
                        }
                        cbAudioFormat.SelectedIndex = 0;
                        if (cbVideoEncoder.Items.Count > 0)
                        {
                            cbVideoEncoder.SelectedIndex = 0;
                        }
                        if (cbAudioEncoder.Items.Count > 0)
                        {
                            cbAudioEncoder.SelectedIndex = 0;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                MessageBox.Show("Unable to detect metadata!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            f.Close();
            this.Enabled = true;
        }

19 Source : BaseEMFunction.cs
with MIT License
from DanzaG

public List<TRVertex> GetTileVertices(short x, short y, short z, bool asCeiling)
        {
            List<TRVertex> vertices = new List<TRVertex>
            {
                new TRVertex { X = (short)(x + SectorSize), Y = y, Z = z },
                new TRVertex { X = x, Y = y, Z = z },
                new TRVertex { X = x, Y = y, Z = (short)(z + SectorSize) },
                new TRVertex { X = (short)(x + SectorSize), Y = y, Z = (short)(z + SectorSize) }
            };

            if (asCeiling)
            {
                vertices.Reverse();
            }

            return vertices;
        }

19 Source : EMMirrorFunction.cs
with MIT License
from DanzaG

private void MirrorFloorData(TR2Level level)
        {
            FDControl control = new FDControl();
            control.ParseFromLevel(level);

            foreach (TR2Room room in level.Rooms)
            {
                // Convert the flattened sector list to 2D
                List<TRRoomSector> sectors = room.SectorList.ToList();
                List<List<TRRoomSector>> sectorMap = new List<List<TRRoomSector>>();
                for (int x = 0; x < room.NumXSectors; x++)
                {
                    sectorMap.Add(new List<TRRoomSector>());
                    for (int z = 0; z < room.NumZSectors; z++)
                    {
                        sectorMap[x].Add(sectors[z + x * room.NumZSectors]);
                    }
                }

                // We are flipping X, so we just reverse the list of sector lists
                sectorMap.Reverse();
                sectors.Clear();
                foreach (List<TRRoomSector> sectorList in sectorMap)
                {
                    sectors.AddRange(sectorList);
                }
                room.SectorList = sectors.ToArray();

                // Change slants and climbable entries
                foreach (TRRoomSector sector in sectors)
                {
                    if (sector.FDIndex != 0)
                    {
                        List<FDEntry> entries = control.Entries[sector.FDIndex];
                        foreach (FDEntry entry in entries)
                        {
                            if (entry is FDSlantEntry slantEntry)
                            {
                                // If the X slope is greater than zero, then its value is added to the floor heights of corners 00 and 01.
                                // If it is less than zero, then its value is subtracted from the floor heights of corners 10 and 11.
                                slantEntry.XSlant *= -1;
                            }
                            else if (entry is FDClimbEntry climbEntry)
                            {
                                // We only need to flip the direction if it's exclusively set in +/- X direction.
                                if (climbEntry.IsNegativeX ^ climbEntry.IsPositiveX)
                                {
                                    climbEntry.IsNegativeX = !(climbEntry.IsPositiveX ^= true);
                                }
                            }
                        }
                    }
                }
            }

            control.WriteToLevel(level);
        }

19 Source : LandmarkImporter.cs
with MIT License
from DanzaG

private IndexedTRObjectTexture CreateTexture(Rectangle rectangle, bool mirrored)
        {
            // Configure the points and reverse them if the level is mirrored
            List<TRObjectTextureVert> vertices = new List<TRObjectTextureVert>
            {
                CreatePoint(0, 0),
                CreatePoint(rectangle.Width, 0),
                CreatePoint(rectangle.Width, rectangle.Height),
                CreatePoint(0, rectangle.Height)
            };

            if (mirrored)
            {
                vertices.Reverse();
            }

            // Make a dummy texture object with the given bounds
            TRObjectTexture texture = new TRObjectTexture
            {
                AtlasAndFlag = 0,
                Attribute = 0,
                Vertices = vertices.ToArray()
            };

            return new IndexedTRObjectTexture
            {
                Index = 0,
                Texture = texture
            };
        }

19 Source : TsMapper.cs
with MIT License
from dariowouters

public void Parse()
        {
            var startTime = DateTime.Now.Ticks;

            if (!Directory.Exists(_gameDir))
            {
                Log.Msg("Could not find Game directory.");
                return;
            }

            Rfs = new RootFileSystem(_gameDir);

            _mods.Reverse(); // Highest priority mods (top) need to be loaded last

            foreach (var mod in _mods)
            {
                if (mod.Load) Rfs.AddSourceFile(mod.ModPath);
            }

            Log.Msg($"Loaded all .scs files in {(DateTime.Now.Ticks - startTime) / TimeSpan.TicksPerMillisecond}ms");

            ParseDefFiles();
            ParseMapFiles();

            ReadLocalizationOptions();

            if (_sectorFiles == null) return;
            var preMapParseTime = DateTime.Now.Ticks;
            Sectors = _sectorFiles.Select(file => new TsSector(this, file)).ToList();
            Sectors.ForEach(sec => sec.Parse());
            Sectors.ForEach(sec => sec.ClearFileData());
            Log.Msg($"It took {(DateTime.Now.Ticks - preMapParseTime) / TimeSpan.TicksPerMillisecond} ms to parse all (*.base)" +
                    $" map files and {(DateTime.Now.Ticks - startTime) / TimeSpan.TicksPerMillisecond} ms total.");
        }

19 Source : SetOperation.cs
with MIT License
from DataObjects-NET

private void PreprocessStructures()
    {
      bool changed = true;
      while (changed)
      {
        changed = false;
        foreach (SetDescriptor setDescriptor in Descriptors.Where(a => a.Field.IsStructure).ToArray())
        {
          var memberInit = setDescriptor.Expression as MemberInitExpression;
          if (memberInit != null)
          {
            changed = true;
            Descriptors.Remove(setDescriptor);
            foreach (Memberreplacedignment binding in memberInit.Bindings)
            {
              FieldInfo f = setDescriptor.Field.Fields.First(a => a.UnderlyingProperty == binding.Member);
              Descriptors.Add(new SetDescriptor(f, setDescriptor.Parameter, binding.Expression));
            }
          }
          else
            foreach (FieldInfo f in setDescriptor.Field.Fields.Where(a => !a.IsStructure))
            {
              changed = true;
              string name = f.Name;
              if (setDescriptor.Field.IsStructure)
                name = name.Remove(0, setDescriptor.Field.Name.Length + 1);
              Descriptors.Remove(setDescriptor);
              Expression ex = setDescriptor.Expression;
              var call = ex as MethodCallExpression;
              if (call != null && call.Method.DeclaringType == typeof(Queryable) &&
                call.Method.Name is "First" or "FirstOrDefault" or "Single" or "SingleOrDefault")
                throw new NotSupportedException("Subqueries with structures are not supported");
              /*ex = call.Arguments[0];
        ParameterExpression parameter = Expression.Parameter(setDescriptor.Expression.Type, "parameter");
        var list = new List<Model.FieldInfo> {f};
        while (list.Last().Parent != setDescriptor.Field)
            list.Add(f.Parent);
        list.Reverse();
        Expression member = parameter;
        foreach (Model.FieldInfo f2 in list)
            member = Expression.MakeMemberAccess(member, f2.UnderlyingProperty);
        LambdaExpression lambda =
            Expression.Lambda(
                typeof (Func<,>).MakeGenericType(parameter.Type, f.ValueType), member, parameter);
        ex = Expression.Call(
            typeof (Queryable), "Select", new[] {parameter.Type, f.ValueType}, ex, lambda);
        ex = Expression.Call(typeof (Queryable), call.Method.Name, new[] {f.ValueType}, ex);*/
              else
              {
                //ex = Expression.Convert(ex, typeof(Structure));
                var list = new List<FieldInfo> { f };
                while (list.Last().Parent != setDescriptor.Field)
                  list.Add(f.Parent);
                list.Reverse();
                Expression member = ex;
                foreach (FieldInfo f2 in list)
                  member = Expression.MakeMemberAccess(member, f2.UnderlyingProperty);
                ex = member;
              }
              Descriptors.Add(new SetDescriptor(f, setDescriptor.Parameter, ex));
            }
        }
      }
    }

19 Source : PartialIndexFilterBuilder.cs
with MIT License
from DataObjects-NET

protected override Expression VisitMemberAccess(MemberExpression originalMemberAccess)
    {
      // Try to collapse series of member access expressions.
      // Finally we should reach original parameter.

      var memberAccess = originalMemberAccess;
      var memberAccessSequence = new List<MemberExpression>();
      for (;;) {
        if (!IsPersistentFieldAccess(memberAccess))
          break;
        memberAccessSequence.Add(memberAccess);
        if (memberAccess.Expression.NodeType!=ExpressionType.MemberAccess)
          break;
        memberAccess = (MemberExpression) memberAccess.Expression;
      }
      if (memberAccessSequence.Count==0 || !IsEnreplacedyParameter(memberAccess.Expression))
        return base.VisitMemberAccess(originalMemberAccess);
      memberAccessSequence.Reverse();
      var fieldName = StringExtensions.Join(".", memberAccessSequence.Select(item => item.Member.Name));
      var field = reflectedType.Fields[fieldName];
      if (field==null)
        throw UnableToTranslate(originalMemberAccess, Strings.MemberAccessSequenceContainsNonPersistentFields);
      if (field.IsEnreplacedy) {
        EnsureCanBeUsedInFilter(originalMemberAccess, field);
        enreplacedyAccessMap[originalMemberAccess] = field;
        return originalMemberAccess;
      }
      if (field.IsPrimitive) {
        EnsureCanBeUsedInFilter(originalMemberAccess, field);
        return BuildFieldAccess(field, false);
      }
      throw UnableToTranslate(originalMemberAccess, Strings.OnlyPrimitiveAndReferenceFieldsAreSupported);
    }

19 Source : SortingPersistActionGenerator.cs
with MIT License
from DataObjects-NET

private void SortAndRemoveLoopEdges(IEnumerable<EnreplacedyState> enreplacedyStates, bool rollbackDifferenceBeforeSort)
    {
      var nodeIndex = new Dictionary<Key, Node<EnreplacedyState>>();
      var graph = new Graph<Node<EnreplacedyState>, Edge<replacedociationInfo>>();

      inboundOnlyStates = new List<EnreplacedyState>();
      outboundOnlyStates = new List<EnreplacedyState>();

      foreach (var state in enreplacedyStates) {
        if (rollbackDifferenceBeforeSort)
          state.RollbackDifference();
        var type = state.Type;
        if (type.IsOutboundOnly)
          outboundOnlyStates.Add(state);
        else if (type.IsInboundOnly)
          inboundOnlyStates.Add(state);
        else {
          var node = new Node<EnreplacedyState>(state);
          graph.Nodes.Add(node);
          nodeIndex.Add(state.Key, node);
        }
      }

      // Add connections
      foreach (var ownerNode in graph.Nodes) {
        var owner = ownerNode.Value;
        var ownerKey = owner.Key;

        var references =
          from replacedociation in owner.Type.GetOwnerreplacedociations()
          where replacedociation.OwnerField.IsEnreplacedy
          select replacedociation;

        foreach (var replacedociation in references) {
          var ownerField = replacedociation.OwnerField;
          var targetKey = owner.Enreplacedy.GetReferenceKey(ownerField);
          Node<EnreplacedyState> targetNode;
          if (targetKey==null || !nodeIndex.TryGetValue(targetKey, out targetNode))
            continue;
          var hierarchy = owner.Enreplacedy.TypeInfo.Hierarchy;
          // If there is self-referencing field of hierarchy root type (important!),
          // we consider there is no dependency, since such insert sequence will preplaced
          // without any modifications
          var skipEdge =
            targetKey.Equals(ownerKey)
              && (hierarchy.InheritanceSchema!=InheritanceSchema.ClreplacedTable
                || ownerField.ValueType==hierarchy.Root.UnderlyingType)
              && !selfReferencingRowRemovalIsError;

          if (skipEdge)
            continue;

          new Edge<replacedociationInfo>(ownerNode, targetNode, replacedociation).Attach();
        }
      }
      //In some cases, 
      List<Edge<replacedociationInfo>> notBreakedEdges = new List<Edge<replacedociationInfo>>();

      //This predicate filter edges where source node value can't be null reference
      Predicate<Edge<replacedociationInfo>> edgeBreaker =
        edge => {
          var replacedociation = edge.Value;
          if (replacedociation.OwnerField.IsNullable)
            return true;
          notBreakedEdges.Add(edge);
          return false;
        };

      // Sort
      var result = TopologicalSorter.Sort(graph, edgeBreaker);

      //Sometimes we have loops after topological sorter.
      //In this case, we add loop nodes in tail of sorted nodes list and broke last edge in loop.
      if (result.HasLoops) {
        sortedNodes = result.SortedNodes.Union(result.LoopNodes).ToList();
        var loopNodes = result.LoopNodes.ToDictionary(el => el as Collections.Graphs.Node);
        notBreakedEdges.Reverse();
        var loopEdgeForBreak = notBreakedEdges.First(edge => loopNodes.ContainsKey(edge.Source) && loopNodes.ContainsKey(edge.Target));
        result.BrokenEdges.Add(loopEdgeForBreak);
      }
      else
        sortedNodes = result.SortedNodes;

      // Remove loop links
      referencesToRestore = new List<Triplet<EnreplacedyState, FieldInfo, Enreplacedy>>();
      foreach (var edge in result.BrokenEdges) {
        var replacedociationInfo = edge.Value;
        var owner = (EnreplacedyState) edge.Source.UntypedValue;
        var target = (EnreplacedyState) edge.Target.UntypedValue;

        referencesToRestore.Add(new Triplet<EnreplacedyState, FieldInfo, Enreplacedy>(
          owner, replacedociationInfo.OwnerField, target.Enreplacedy));

        var enreplacedy = owner.Enreplacedy;
        enreplacedy.SystemBeforeTupleChange();
        enreplacedy
          .GetFieldAccessor(replacedociationInfo.OwnerField)
          .SetUntypedValue(enreplacedy, null);
      }
    }

19 Source : TypeInfo.cs
with MIT License
from DataObjects-NET

public IList<TypeInfo> GetAncestors()
    {
      if (IsLocked)
        return ancestors;

      var result = new List<TypeInfo>();
      var ancestor = model.Types.FindAncestor(this);
      // TODO: Refactor
      while (ancestor!=null) {
        result.Add(ancestor);
        ancestor = model.Types.FindAncestor(ancestor);
      }
      result.Reverse();
      return result;
    }

19 Source : ReferenceUpdater.cs
with MIT License
from DataObjects-NET

private void UpdateTypeAllAncestors(StoredTypeInfo type)
    {
      var result = new List<StoredTypeInfo>();
      var currentAncestor = type.Ancestor;
      while (currentAncestor != null) {
        result.Add(currentAncestor);
        currentAncestor = currentAncestor.Ancestor;
      }
      result.Reverse();
      type.AllAncestors = result.ToArray();
    }

19 Source : FormNodeView.cs
with GNU Lesser General Public License v3.0
from dathlin

private string[] GetTreePath( TreeNode treeNode )
        {
            List<string> paths = new List<string>( );
            while (true)
            {
                if (treeNode != null)
                {
                    paths.Add( treeNode.Text );
                    treeNode = treeNode.Parent;
                }
                else
                {
                    break;
                }
            }
            paths.Reverse( );
            return paths.ToArray( );
        }

19 Source : SharpNodeServer.cs
with GNU Lesser General Public License v3.0
from dathlin

private string[] GetXmlPath( XElement element )
        {
            List<string> paths = new List<string>( );
            while (true)
            {
                if(element != null)
                {
                    if(element.Attribute( "Name" ) == null)
                    {
                        break;
                    }
                    paths.Add( element.Attribute("Name").Value );
                    element = element.Parent;
                }
                else
                {
                    break;
                }
            }
            paths.Reverse( );
            return paths.ToArray( );
        }

19 Source : TenantHostedServiceManager.cs
with MIT License
from dazinator

public async Task StopAsync(CancellationToken cancellationToken = default)
        {
            _logger.LogInformation("Stopping tenant hosted services");

            using (var cts = new CancellationTokenSource(StoppingTimeout))
            using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken))
            {
                var token = linkedCts.Token;
                //// Trigger IApplicationLifetime.ApplicationStopping
                //_applicationLifetime?.StopApplication();

                IList<Exception> exceptions = new List<Exception>();
                if (HostedServices != null) // Started?
                {
                    HostedServices.Reverse();
                    foreach (var hostedService in HostedServices)
                    {
                        token.ThrowIfCancellationRequested();
                        try
                        {
                            await hostedService.StopAsync(token).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            exceptions.Add(ex);
                        }
                    }
                }

                token.ThrowIfCancellationRequested();
                // await _hostLifetime.StopAsync(token);

                // Fire IApplicationLifetime.Stopped
                // _applicationLifetime?.NotifyStopped();

                if (exceptions.Count > 0)
                {
                    var ex = new AggregateException("One or more hosted services failed to stop.", exceptions);
                    _logger.LogError(ex, ex.Message);
                    throw ex;
                }
            }

            _logger.LogInformation("Tenant hosted services were stopped.");
        }

19 Source : PathFinder.cs
with MIT License
from dbrizov

private static List<Tile> BacktrackToPath(Tile end)
        {
            Tile current = end;
            List<Tile> path = new List<Tile>();

            while (current != null)
            {
                path.Add(current);
                current = current.PrevTile;
            }

            path.Reverse();

            return path;
        }

19 Source : Mesh.cs
with GNU General Public License v3.0
from dd-bim

public int? AddFace(IReadOnlyList<int> vertices)
        {
            if(vertices.Count < 3)
            { return null; }

            // Vertices prüfen (auf Wiederholung)
            var verts = new List<int> { vertices[0] };
            foreach(int v in vertices)
            {
                // evtl. durch Grenzwertunterschreitung entfernte Kante ignorieren
                if(verts[verts.Count - 1] != v)
                {
                    // ein Vertex darf nur einmal im Face vorhanden sein
                    if(verts.Contains(v))
                    { return null; }
                    verts.Add(v);
                }
            }
            int vcnt = verts.Count;
            if(vcnt < 3)
            { return null; }

            // ersten Punkt anhängen
            verts.Add(verts[0]);

            // evtl. Reihenfolge umkehren
            if(this.IsShape)
            {
                // da hier keine Richtung definierbar ist, muss bei vorhandener Kante geprüft werden ob umgedrehte Richtung möglich
                int fcnt = 0, rcnt = 0;

                for(int i = 1; i < verts.Count; i++)
                {
                    var e = new TupleIdx(verts[i - 1], verts[i]);
                    if(this.EdgeIndices.ContainsKey(e))
                    {
                        fcnt++;
                    }
                    else if(this.EdgeIndices.ContainsKey(TupleIdx.Flipped(e)))
                    {
                        rcnt++;
                    }
                }
                if(fcnt > 0)
                {
                    // keien Drehung Möglich
                    if(rcnt > 0)
                    { return null; }
                    verts.Reverse();
                }
            }
            else
            {
                // 2D müssen immer positiven Z-Wert in Normale haben
                //var a = this.Points[verts[1]];
                //var b = this.Points[verts[2]];
                //var c = this.Points[verts[0]];
                //double normalZ = ((a.X - c.X) * (b.Y - c.Y)) - ((a.Y - c.Y) * (b.X - c.X));

                if(Vector3.Cross(this.Points[verts[1]] - this.Points[verts[0]], this.Points[verts[2]] - this.Points[verts[0]]).Z < 0.0)
                {
                    verts.Reverse();
                }

                // wenn Kante vorhanden, abbrechen
                for(int i = 1; i < verts.Count; i++)
                {
                    if(this.EdgeIndices.ContainsKey(new TupleIdx(verts[i - 1], verts[i])))
                    {
                        return null;
                    }
                }
            }

            // Kanten hinzufügen
            int face = this.FaceEdges.Count;
            int fst = this.EdgeFaces.Count;
            this.FaceEdges.Add(fst);
            for(int i = 1; i < verts.Count; i++)
            {
                var e = new TupleIdx(verts[i - 1], verts[i]);

                // Vertex der Halbkante zuordnen (nur einmal nötig)
                if(this.VertexEdges[e.Idx1] < 0)
                { this.VertexEdges[e.Idx1] = fst + i - 1; }

                // Kante erzeugen
                this.EdgeIndices.Add(e, fst + i - 1);
                this.EdgeVertices.Add(e.Idx1);
                this.EdgeNexts.Add(fst + (i % vcnt));
                this.EdgeFaces.Add(face);
            }

            if(vcnt > this.MaxFaceCorners)
            { this.MaxFaceCorners = vcnt; }
            if(vcnt < this.MinFaceCorners)
            { this.MinFaceCorners = vcnt; }

            return face;
        }

19 Source : GameObject.cs
with GNU General Public License v3.0
from deathkiller

public List<int> GetIndexPathOfChild(GameObject child)
		{
			List<int> path = new List<int>();
			while (child.parent != null && child != this)
			{
				path.Add(child.parent.children.IndexOf(child));
				child = child.parent;
			}
			path.Reverse();
			return path;
		}

19 Source : Scene.cs
with GNU General Public License v3.0
from deathkiller

private static void OnGameObjectsRemoved(GameObjectGroupEventArgs args)
		{
			// Fire a global event to indicate that the objects are going to be shut down
			GameObjectsRemoved?.Invoke(current, args);

			// Gather a list of components to deactivate
			int objCount = 0;
			List<ICmpInitializable> initList = new List<ICmpInitializable>();
			foreach (GameObject obj in args.Objects) {
				if (!obj.ActiveSingle && !obj.Disposed) continue;
				obj.GatherInitComponents(initList, false);
				objCount++;
			}

			// If we collected components from more than one object, sort by exec order.
			// Otherwise, we can safely replacedume that the list is already sorted.
			if (objCount > 1)
				Component.ExecOrder.SortTypedItems(initList, item => item.GetType(), true);
			else
				initList.Reverse();

			// Invoke the init event on all gathered components in the right order
			foreach (ICmpInitializable component in initList)
				component.OnShutdown(Component.ShutdownContext.Deactivate);
		}

19 Source : StackTrace.cs
with BSD 3-Clause "New" or "Revised" License
from debug-sharp

private static Dictionary<string, ExceptionToRender> _completeExceptionsOrderByRelationships (Dictionary<string, object[]> exceptions, bool catched = true) {
			Dictionary<string, ExceptionToRender> result = new Dictionary<string, ExceptionToRender>();
			Dictionary<string, ExceptionToRender> reversedResult = new Dictionary<string, ExceptionToRender>();
			Exception causedByException;
			Exception triggeredException;
			string triggeredExceptionKey;
			foreach (var item in exceptions) {
				causedByException = item.Value[0] as Exception;
				triggeredException = null;
				if (item.Value.Length > 1) {
					triggeredExceptionKey = item.Value[1].ToString();
					if (exceptions.ContainsKey(triggeredExceptionKey)) {
						triggeredException = item.Value[2] as Exception;
					}
					if (reversedResult.ContainsKey(triggeredExceptionKey)) continue;
					reversedResult.Add(triggeredExceptionKey, new ExceptionToRender {
						Exception = triggeredException,
						CausedBy = causedByException,
						Catched = catched
					});
				}
			}
			foreach (var item in exceptions) {
				if (!reversedResult.ContainsKey(item.Key)) {
					reversedResult.Add(item.Key, new ExceptionToRender {
						Exception = item.Value[0] as Exception,
						CausedBy = null,
						Catched = catched
					});
					// break;?
				}
			}
			List<string> resultKeysOrdered = reversedResult.Keys.ToList<string>();
			resultKeysOrdered.Reverse();
			foreach (string resultKey in resultKeysOrdered) {
				result.Add(resultKey, reversedResult[resultKey]);
			}
			return result;
		}

19 Source : BlockContainer.cs
with MIT License
from deepakkumar1984

public void SortBlocks(bool deleteUnreachableBlocks = false)
		{
			if (Blocks.Count < 2)
				return;

			// Visit blocks in post-order
			BitSet visited = new BitSet(Blocks.Count);
			List<Block> postOrder = new List<Block>();
			
			Action<Block> visit = null;
			visit = delegate(Block block) {
				Debug.replacedert(block.Parent == this);
				if (!visited[block.ChildIndex]) {
					visited[block.ChildIndex] = true;

					foreach (var branch in block.Descendants.OfType<Branch>()) {
						if (branch.TargetBlock.Parent == this) {
							visit(branch.TargetBlock);
						}
					}

					postOrder.Add(block);
				}
			};
			visit(EntryPoint);
			
			postOrder.Reverse();
			if (!deleteUnreachableBlocks) {
				for (int i = 0; i < Blocks.Count; i++) {
					if (!visited[i])
						postOrder.Add(Blocks[i]);
				}
			}
			Debug.replacedert(postOrder[0] == Blocks[0]);
			Blocks.ReplaceList(postOrder);
		}

19 Source : MXNet.cs
with Apache License 2.0
from deepakkumar1984

private static (string, string) c2pyerror(string err_msg)
        {
            var arr = err_msg.Split('\n').ToList();
            if (arr.Last() == "")
            {
                arr.RemoveAt(arr.Count - 1);
            }

            var err_type = _find_error_type(arr[0]);
            var trace_mode = false;
            var stack_trace = new List<string>();
            var message = new List<string>();
            foreach (var line in arr)
            {
                if (trace_mode)
                {
                    if (line.StartsWith("  "))
                    {
                        stack_trace.Add(line);
                    }
                    else
                    {
                        trace_mode = false;
                    }
                }
                if (!trace_mode)
                {
                    if (line.StartsWith("Stack trace"))
                    {
                        trace_mode = true;
                    }
                    else
                    {
                        message.Add(line);
                    }
                }
            }

            var out_msg = "";
            if (stack_trace.Count > 0)
            {
                out_msg += "Traceback (most recent call last):\n";
                stack_trace.Reverse();
                out_msg += string.Join("\n", stack_trace) + "\n";
            }

            out_msg += string.Join("\n", message);
            return (out_msg, err_type);
        }

19 Source : BindableCollection.cs
with MIT License
from delight-dev

public virtual void Reverse()
        {
            DataList.Reverse();
        }

19 Source : Trainer.cs
with MIT License
from Dentrax

private void OrderDistances(int count) {
            this.m_results = this.m_results.OrderByDescending(x => x.Distance).ToList();
            this.m_results.Reverse();
        }

19 Source : State.cs
with MIT License
from deveel

private string[] BuildPath() {
			var names = new List<string>();

			var current = this;
			while (current != null) {
				var name = GetStateName(current);
				names.Add(name);

				current = current.Previous;
			}

			names.Reverse();
			return names.ToArray();
		}

19 Source : ExecutionReport.cs
with MIT License
from deveel

internal static ExecutionReport Build(State finalState) {
			var states = new List<State>();
			State current = finalState;
			while (current != null) {
				states.Add(current);
				current = current.Previous;
			}

			states.Reverse();

			return new ExecutionReport(states.Select(x => new ReportNode(x)));
		}

See More Examples