int.CompareTo(int)

Here are the examples of the csharp api int.CompareTo(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1221 Examples 7

19 Source : Window1.xaml.cs
with MIT License
from bstollnitz

public int Compare(object x, object y)
		{
			string str1 = x.ToString();
			string str2 = y.ToString();

			int int1 = GetNumberAtBeginning(str1);
			int int2 = GetNumberAtBeginning(str2);

			// strings start with same number or don't start with numbers
			if (int1 == int2)
			{
				return str1.CompareTo(str2); // compare the strings
			}
			// strings start with different numbers
			else if ((int1 != -1) && (int2 != -1))
			{
				return int1.CompareTo(int2); // compare the numbers
			}
			// first string does not start with number
			else if (int1 == -1)
			{
				return 1; // second string goes first
			}
			// second string does not start with number
			else 
			{
				return -1; // first string goes first
			}
		}

19 Source : ShortChannelId.cs
with MIT License
from btcpayserver

public int CompareTo(ShortChannelId other)
        {
            if (other == null)
                return 1;

            var c1 = BlockHeight.CompareTo(other.BlockHeight);
            if (c1 != 0)
                return c1;

            var c2 = BlockIndex.CompareTo(other.BlockIndex);
            if (c2 != 0)
                return c2;

            var c3 = TxOutIndex.CompareTo(other.TxOutIndex);
            if (c3 != 0)
                return c3;

            return 0;
        }

19 Source : Huffman.cs
with MIT License
from Bunny83

public int CompareTo(INode other)
            {
                return other.Weight.CompareTo(Weight);
            }

19 Source : Utils.cs
with MIT License
from cabarius

public int Compare(string left, string right) {
            if (int.TryParse(left, out var l) && int.TryParse(right, out var r))
                return l.CompareTo(r);
            else
                return left.CompareTo(right);
        }

19 Source : Buffers.cs
with MIT License
from CatLib

public int Compare(KeyValuePair<string, uint> xPair, KeyValuePair<string, uint> yPair)
			{
				var x = xPair.Key;
				var y = yPair.Key;

				for (int i = x.Length - 1, j = y.Length - 1; i >= 0 & j >= 0; i--, j--) {
					if (x [i] < y [j]) {
						return -1;
					}

					if (x [i] > y [j]) {
						return +1;
					}
				}

				return y.Length.CompareTo (x.Length);
			}

19 Source : CodeFixService.cs
with Apache License 2.0
from cdy816

public async Task<ImmutableArray<CodeFixCollection>> GetFixesAsync(Doreplacedent doreplacedent, TextSpan range, bool includeConfigurationFixes, bool isBlocking, CancellationToken cancellationToken)
            {
                // REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back
                // current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information
                // (if it is up-to-date) or synchronously do the work at the spot.
                //
                // this design's weakness is that each side don't have enough information to narrow down works to do. it will most likely always do more works than needed.
                // sometimes way more than it is needed. (compilation)

                // group diagnostics by their diagnostics span
                // invariant: later code gathers & runs CodeFixProviders for diagnostics with one identical diagnostics span (that gets set later as CodeFixCollection's TextSpan)
                Dictionary<TextSpan, List<DiagnosticData>>? aggregatedDiagnostics = null;
                foreach (var diagnostic in await _diagnosticService.GetDiagnosticsForSpanAsync(doreplacedent, range, diagnosticIdOpt: null, includeConfigurationFixes, cancellationToken: cancellationToken).ConfigureAwait(false))
                {
                    if (diagnostic.IsSuppressed)
                    {
                        continue;
                    }

                    cancellationToken.ThrowIfCancellationRequested();

                    aggregatedDiagnostics ??= new Dictionary<TextSpan, List<DiagnosticData>>();
                    aggregatedDiagnostics.GetOrAdd(diagnostic.GetTextSpan(), _ => new List<DiagnosticData>()).Add(diagnostic);
                }

                if (aggregatedDiagnostics == null)
                {
                    return ImmutableArray<CodeFixCollection>.Empty;
                }

                // append fixes for all diagnostics with the same diagnostics span
                using var resultDisposer = ArrayBuilder<CodeFixCollection>.GetInstance(out var result);
                foreach (var spanAndDiagnostic in aggregatedDiagnostics)
                {
                    await AppendFixesAsync(
                        doreplacedent, spanAndDiagnostic.Key, spanAndDiagnostic.Value, fixAllForInSpan: false, isBlocking,
                        result, cancellationToken).ConfigureAwait(false);
                }

                if (result.Count > 0)
                {
                    // sort the result to the order defined by the fixers
                    var priorityMap = _fixerPriorityMap[doreplacedent.Project.Language].Value;
                    result.Sort((d1, d2) => GetValue(d1).CompareTo(GetValue(d2)));

                    int GetValue(CodeFixCollection c)
                        => priorityMap!.TryGetValue((CodeFixProvider)c.Provider, out var value) ? value : int.MaxValue;
                }

                if (includeConfigurationFixes)
                {
                    foreach (var spanAndDiagnostic in aggregatedDiagnostics)
                    {
                        await AppendConfigurationsAsync(
                            doreplacedent, spanAndDiagnostic.Key, spanAndDiagnostic.Value,
                            result, cancellationToken).ConfigureAwait(false);
                    }
                }

                return result.ToImmutable();
            }

19 Source : UnicodeString.cs
with MIT License
from Centvrio

public int CompareTo(UnicodeString other) => Code.CompareTo(other.Code);

19 Source : UnicodeString.cs
with MIT License
from Centvrio

public int CompareTo(int other) => Code.CompareTo(other);

19 Source : SmartTransaction.cs
with GNU General Public License v3.0
from chaincase-app

public static IComparer<SmartTransaction> GetBlockchainComparer()
		{
			return Comparer<SmartTransaction>.Create((a, b) =>
			{
				var heightCompareResult = a.Height.CompareTo(b.Height);
				if (heightCompareResult != 0)
				{
					return heightCompareResult;
				}

				// If mempool this should be 0, so they should be equal so no worry about it.
				var blockIndexCompareResult = a.BlockIndex.CompareTo(b.BlockIndex);
				if (blockIndexCompareResult != 0)
				{
					return blockIndexCompareResult;
				}

				var firstSeenCompareResult = a.FirstSeen.CompareTo(b.FirstSeen);
				return firstSeenCompareResult;
			});
		}

19 Source : Height.cs
with GNU General Public License v3.0
from chaincase-app

public int CompareTo(Height other) => Value.CompareTo(other.Value);

19 Source : Height.cs
with GNU General Public License v3.0
from chaincase-app

public int CompareTo(int other)
		{
			return Value.CompareTo(other);
		}

19 Source : ListExtensionTests.cs
with GNU General Public License v3.0
from chaincase-app

public int CompareTo([AllowNull] ReverseComparable other)
			{
				return other.Value.CompareTo(Value);
			}

19 Source : H264Depacketiser.cs
with MIT License
from chatop2020

protected virtual List<byte[]> ProcessH264Payload(byte[] rtp_payload, ushort seqNum, uint rtp_timestamp, int rtp_marker, out bool isKeyFrame)
        {
            if (previous_timestamp != rtp_timestamp && previous_timestamp > 0)
            {
                temporary_rtp_payloads.Clear();
                previous_timestamp = 0;
                fragmented_nal.SetLength(0);
            }

            // Add to the list of payloads for the current Frame of video
            temporary_rtp_payloads.Add(new KeyValuePair<int, byte[]>(seqNum, rtp_payload)); // TODO could optimise this and go direct to Process Frame if just 1 packet in frame
            if (rtp_marker == 1)
            {
                //Reorder to prevent UDP incorrect package order
                if (temporary_rtp_payloads.Count > 1)
                {
                    temporary_rtp_payloads.Sort((a, b) => { return a.Key.CompareTo(b.Key); });
                }

                // End Marker is set. Process the list of RTP Packets (forming 1 RTP frame) and save the NALs to a file
                List<byte[]> nal_units = ProcessH264PayloadFrame(temporary_rtp_payloads, out isKeyFrame);
                temporary_rtp_payloads.Clear();
                previous_timestamp = 0;
                fragmented_nal.SetLength(0);

                return nal_units;
            }
            else
            {
                isKeyFrame = false;
                previous_timestamp = rtp_timestamp;
                return null; // we don't have a frame yet. Keep acreplacedulating RTP packets
            }
        }

19 Source : Scheduler.cs
with MIT License
from cheliotk

List<int> GetListOfRegisteredPriorityValuesAtQ(Stepper.StepperQueueOrder stepperQ){
                List<int> stepperPVals = new List<int>();
                    
                if(steppers.ContainsKey(stepperQ))
                    stepperPVals.AddRange(steppers[stepperQ].Keys);
                
                if(steppersEveryTick.ContainsKey(stepperQ))
                    stepperPVals.AddRange(steppersEveryTick[stepperQ].Keys);

                HashSet<int> stepperPValsUniqueTemp = new HashSet<int>(stepperPVals);
                List<int> stepperPValsUnique = new List<int>(stepperPValsUniqueTemp);
                stepperPValsUnique.Sort((a,b) => a.CompareTo(b));

                return stepperPValsUnique;
            }

19 Source : Stepper.cs
with MIT License
from cheliotk

public int CompareTo(Stepper otherStepper)
            {
                // A null value means that this object is greater.
                if (otherStepper == null)
                    return 1;
                    
                else
                    return this.priority.CompareTo(otherStepper.priority);
            }

19 Source : AtlasBuilder.cs
with MIT License
from ChevyRay

public Atlas Build(int pad)
        {
            var packer = new RectanglePacker(maxSize, maxSize, packCount);

            //This ID is used to keep the rectangles ordered (we need to unpack in the same order we packed)
            int nextID = 0;

            //Add all the bitmaps (padding them)
            foreach (var pair in bitmaps)
            {
                RectangleI rect;
                if (!trims.TryGetValue(pair.Value, out rect))
                    rect = new RectangleI(pair.Value.Width, pair.Value.Height);
                packer.Add(++nextID, rect.W + pad, rect.H + pad, true);
            }

            //Add all the font characters (padding them)
            foreach (var pair in fonts)
            {
                FontChar chr;
                for (int i = 0; i < pair.Value.CharCount; ++i)
                {
                    pair.Value.GetCharInfoAt(i, out chr);
                    if (!pair.Value.IsEmpty(chr.Char))
                        packer.Add(++nextID, chr.Width + pad, chr.Height + pad, true);
                }
            }

            //Add all the tiles (padding them)
            foreach (var pair in tiles)
            {
                var tileset = pair.Value;
                RectangleI rect;
                for (int y = 0; y < tileset.Rows; ++y)
                {
                    for (int x = 0; x < tileset.Cols; ++x)
                    {
                        var tile = tileset.Bitmaps[x, y];
                        if (tile != null)
                        {
                            if (!trims.TryGetValue(tile, out rect))
                                rect = new RectangleI(tile.Width, tile.Height);
                            packer.Add(++nextID, rect.W + pad, rect.H + pad, true);
                        }
                    }
                }
            }

            //Pack the rectangles
            if (!packer.Pack())
                return null;

            //Sort the packed rectangles so they're in the same order we added them
            var packed = new Packed[packer.PackedCount];
            for (int i = 0; i < packed.Length; ++i)
                packer.GetPacked(i, out packed[i].ID, out packed[i].Rect);
            Array.Sort(packed, (a, b) => a.ID.CompareTo(b.ID));

            //Get the atlas size
            int atlasW, atlasH;
            packer.GetBounds(out atlasW, out atlasH);
            atlasW = atlasW.ToPowerOf2();
            atlasH = atlasH.ToPowerOf2();

            ///Create the atlas with an empty texture for now
            var atlas = new Atlas(new Texture2D(atlasW, atlasH, TextureFormat.RGBA));
            var atlasBitmap = new Bitmap(atlasW, atlasH);
            var rotBitmap = new Bitmap(1, 1);
            var trimBitmap = new Bitmap(1, 1);

            //Reset the ID so we get the correct packed rectangles as we go
            nextID = 0;

            AtlasImage AddImage(string name, Bitmap bitmap)
            {
                RectangleI trim;
                if (!trims.TryGetValue(bitmap, out trim))
                    trim = new RectangleI(bitmap.Width, bitmap.Height);

                //Get the rectangle and unpad it
                var rect = packed[nextID++].Rect;
                rect.W -= pad;
                rect.H -= pad;

                var img = atlas.AddImage(name, bitmap.Width, bitmap.Height, trim.X, trim.Y, trim.W, trim.H, rect, trim.W != rect.W);

                //Blit the bitmap onto the atlas, optionally rotating it
                if (trim.W != rect.W)
                {
                    //Rotate the bitmap, trimming first if the bitmap was trimmed
                    if (trim.W < bitmap.Width || trim.H < bitmap.Height)
                    {
                        bitmap.GetSubRect(trimBitmap, trim);
                        trimBitmap.RotateRight(rotBitmap);
                    }
                    else
                        bitmap.RotateRight(rotBitmap);

                    atlasBitmap.CopyPixels(rotBitmap, rect.X, rect.Y);
                }
                else
                    atlasBitmap.CopyPixels(bitmap, trim.X, trim.Y, trim.W, trim.H, rect.X, rect.Y);

                return img;
            }

            //Add the images
            foreach (var pair in bitmaps)
                AddImage(pair.Key, pair.Value);

            //Add the fonts
            Bitmap charBitmap = null;
            foreach (var pair in fonts)
            {
                var size = pair.Value;

                //This is the bitmap we'll render the character onto
                if (charBitmap == null)
                    charBitmap = new Bitmap(size.MaxCharW, size.MaxCharH);
                else
                    charBitmap.Resize(size.MaxCharW, size.MaxCharH);

                //Create an atlas font to populate with the characters
                var font = atlas.AddFont(pair.Key, size.Ascent, size.Descent, size.LineGap);
                FontChar chr;
                RectangleI rect;
                for (int i = 0; i < size.CharCount; ++i)
                {
                    size.GetCharInfoAt(i, out chr);

                    if (!size.IsEmpty(chr.Char))
                    {
                        //Get the packed rectangle and unpad it
                        rect = packed[nextID++].Rect;
                        rect.W -= pad;
                        rect.H -= pad;

                        //Rasterize the character and optionally rotate it before blitting
                        size.GetPixels(chr.Char, charBitmap, fontsToPremultiply.Contains(size));
                        if (chr.Width != rect.W)
                        {
                            charBitmap.RotateRight(rotBitmap);
                            atlasBitmap.CopyPixels(rotBitmap, rect.X, rect.Y);
                        }
                        else
                            atlasBitmap.CopyPixels(charBitmap, rect.X, rect.Y);
                    }
                    else
                        rect = RectangleI.Empty;
                    
                    var atlasChar = font.AddChar(chr.Char, chr.Width, chr.Height, chr.Advance, chr.OffsetX, chr.OffsetY, rect, chr.Width != rect.W);

                    //Set character kerning
                    for (int j = 0; j < size.CharCount; ++j)
                    {
                        char nextChar = size.GetCharAt(j);
                        int kern = size.GetKerning(chr.Char, nextChar);
                        if (kern != 0)
                            atlasChar.SetKerning(nextChar, kern);
                    }
                }
            }

            //Add the tiles
            foreach (var pair in tiles)
            {
                var prefix = pair.Key;
                var tileset = pair.Value;
                var atlasTiles = atlas.AddTiles(prefix, tileset.Cols, tileset.Rows, tileset.TileWidth, tileset.TileHeight);
                
                for (int y = 0; y < tileset.Rows; ++y)
                {
                    for (int x = 0; x < tileset.Cols; ++x)
                    {
                        var tile = tileset.Bitmaps[x, y];
                        if (tile != null)
                        {
                            var image = AddImage($"{prefix}:{x},{y}", tile);
                            atlasTiles.SetTile(x, y, image);
                        }
                    }
                }
            }

            //Now that the bitmap is rendered, upload it to the texture
            atlas.Texture.SetPixels(atlasBitmap);

            return atlas;
        }

19 Source : CompositeWorkItem.cs
with MIT License
from chstetco

public int Compare(UnityWorkItem x, UnityWorkItem y)
            {
                var xKey = int.MaxValue;
                var yKey = int.MaxValue;

                if (x.Test.Properties.ContainsKey(PropertyNames.Order))
                    xKey = (int)x.Test.Properties[PropertyNames.Order][0];

                if (y.Test.Properties.ContainsKey(PropertyNames.Order))
                    yKey = (int)y.Test.Properties[PropertyNames.Order][0];

                return xKey.CompareTo(yKey);
            }

19 Source : ItemsLayer.cs
with MIT License
from chstetco

public int CompareTo(LayerZOrder other)
        {
            if (m_Layer == other.m_Layer)
                return m_ZOrder.CompareTo(other.m_ZOrder);
            return m_Layer.CompareTo(other.m_Layer);
        }

19 Source : BFI002 Omit from bibliography and sort by reference type.cs
with MIT License
from Citavi

public int Compare(Citation x, Citation y)
		{

			//First we make sure we are comparing BibliographyCitations only
			var xBibliographyCitation = x as BibliographyCitation;
			var yBibliographyCitation = y as BibliographyCitation;

			if (xBibliographyCitation == null || yBibliographyCitation == null) return 0;
			var xReference = xBibliographyCitation.Reference;
			var yReference = yBibliographyCitation.Reference;
			if (xReference == null || yReference == null) return 0;

			//1st Comparer
			var defaultCitationComparer = CitationComparer.AuthorYearreplacedleOrNoAuthorThenreplacedleYearAscending;


			//2nd Comparer, if first yields 0
			var yearreplacedleVolumeSortDescriptors = new List<PropertySortDescriptor<Reference>>();
			yearreplacedleVolumeSortDescriptors.Add(new PropertySortDescriptor<Reference>(ReferencePropertyDescriptor.YearResolved));
			yearreplacedleVolumeSortDescriptors.Add(new PropertySortDescriptor<Reference>(ReferencePropertyDescriptor.replacedle));
			yearreplacedleVolumeSortDescriptors.Add(new PropertySortDescriptor<Reference>(ReferencePropertyDescriptor.Volume));
			yearreplacedleVolumeSortDescriptors.Add(new PropertySortDescriptor<Reference>(ReferencePropertyDescriptor.Number));
			var yearreplacedleVolumeComparer = new CitationComparer(yearreplacedleVolumeSortDescriptors);


			var xSection = GetBibliographySection(xReference);
			var ySection = GetBibliographySection(yReference);

			if (xSection == -1) xBibliographyCitation.NoBib = true;
			if (ySection == -1) yBibliographyCitation.NoBib = true;

			var sectionComparison = xSection.CompareTo(ySection);

			if (sectionComparison == 0)
			{
				var defaultCompareResult = defaultCitationComparer.Compare(x, y);
			if (defaultCompareResult != 0) return defaultCompareResult;
			
			return yearreplacedleVolumeComparer.Compare(x, y);
			}
			else
			{
				return sectionComparison;
			}
		}

19 Source : BSO005_SortBibliography_CourtDecisionsByRank.cs
with MIT License
from Citavi

public int Compare(Citation x, Citation y)
		{
			// Dieses Script kann sowohl zur Sortierung des Literaturverzeichnisses 
			// als auch von Mehrfachnachweisen im Text und in der Fußnote eingesetzt werden.
			
			//1. Alles ausser Gesetz/Verordnung und Gerichtsentscheidungen
			//2. Gesetz/Verordnung
			//3. Gerichtsentscheidungen
			
			//wenn beide unter 3. fallen:
			//Freitextfeld 1 auswerten ("Instanz", intern CustomField1) ODER Gericht (intern "Organizations"), s. Zeile 34, "courtField"
			//1. Bundesverfreplacedungsgericht
			//2. Bundesgerichtshof
			//3. Oberlandesgericht
			//4. Landgericht
			//5. Amtsgericht
			
			//(die genauen Schreibweisen können in den Zeilen 120-133 eingestellt werden)
			//wenn beide dieselbe Instanz haben absteigend nach Autor, Herausgeber, Insreplacedution !
			
			ReferencePropertyId courtField = ReferencePropertyId.Organizations; //alternativ: ReferencePropertyId.CustomField1

			if (x == null || y == null) return 0;
			var xReference = x.Reference;
			var yReference = y.Reference;
			if (xReference == null || yReference == null) return 0;		
			
			var defaultComparer = CitationComparer.AuthorYearreplacedleOrNoAuthorThenreplacedleYearAscending;
		
			
			var xIsLiterature = xReference.ReferenceType != ReferenceType.StatuteOrRegulation && xReference.ReferenceType != ReferenceType.CourtDecision;
			var yIsLiterature = yReference.ReferenceType != ReferenceType.StatuteOrRegulation && yReference.ReferenceType != ReferenceType.CourtDecision;
			
			var xIsStatuteOrRegulation = xReference.ReferenceType == ReferenceType.StatuteOrRegulation;
			var yIsStatuteOrRegulation = yReference.ReferenceType == ReferenceType.StatuteOrRegulation;
			
			var xIsCourtDecision = xReference.ReferenceType == ReferenceType.CourtDecision;
			var yIsCourtDecision = yReference.ReferenceType == ReferenceType.CourtDecision;
			
			if (xIsCourtDecision && yIsCourtDecision)
			{
				//spezielle Sortierung für Gerichtsentscheidungen:
				
				int xCourtRanking = 99;
				int yCourtRanking = 99;
				
				if (courtField == ReferencePropertyId.Organizations)
				{
					IEnumerable<Person> xCourts = xReference.GetValue(courtField) as IEnumerable<Person>;
					IEnumerable<Person> yCourts = yReference.GetValue(courtField) as IEnumerable<Person>;
					
					Person xCourt = xCourts == null ? null : xCourts.FirstOrDefault();
					Person yCourt = yCourts == null ? null : yCourts.FirstOrDefault();
					
					xCourtRanking = GetCourtRanking(xCourt);
					yCourtRanking = GetCourtRanking(yCourt);
				}
				else
				{
					string xCourt = xReference.GetValue(courtField) as string;
					string yCourt = yReference.GetValue(courtField) as string;
					
					xCourtRanking = GetCourtRanking(xCourt);
					yCourtRanking = GetCourtRanking(yCourt);
				}

				
				
				if (xCourtRanking == yCourtRanking)
				{
					return defaultComparer.Compare(x, y);
				}
				else
				{
					return xCourtRanking.CompareTo(yCourtRanking);
				}	
				
			}
			else if (xIsCourtDecision && !yIsCourtDecision)
			{
				return 1;
			}
			else if (!xIsCourtDecision && yIsCourtDecision)
			{
				return -1;
			}
			else if (xIsStatuteOrRegulation && yIsLiterature)
			{
				return 1;
			}
			else if (xIsLiterature && yIsStatuteOrRegulation)
			{
				return -1;
			}
			else
			{
				//z.B. beide Literatur oder beide Gesetz/Verordnung
				return defaultComparer.Compare(x, y);
			}

		}

19 Source : BSO006 Sort by first author, author with 1 co-author, multiple co-authors.cs
with MIT License
from Citavi

private int ComparePersons(Person xPerson, Person yPerson)
        {
            if (xPerson == null || yPerson == null) return 0;

            StringComparer defaultStringComparer = StringComparer.Create(_cultureForSorting, true);

            var xLastNameForSortingResolved = xPerson.GetLastNameForSortingResolved();
            var yLastNameForSortingResolved = yPerson.GetLastNameForSortingResolved();

            //var lastNameCompareResult = xLastNameForSortingResolved.CompareTo(yLastNameForSortingResolved);
            var lastNameCompareResult = defaultStringComparer.Compare(xLastNameForSortingResolved, yLastNameForSortingResolved);
            if (lastNameCompareResult != 0) return lastNameCompareResult;

            if (_cultureForSorting == CultureInfo.GetCultureInfo("de-DE"))
            {
                var lengthCompareResult = xLastNameForSortingResolved.CompareTo(yLastNameForSortingResolved);
                if (lengthCompareResult != 0) return lengthCompareResult;
            }

            var xFirstAndMiddleName = ConcatNonEmptyStrings(" ", new string[] { xPerson.FirstName, xPerson.MiddleName, xPerson.Prefix, xPerson.Suffix });
            var yFirstAndMiddleName = ConcatNonEmptyStrings(" ", new string[] { yPerson.FirstName, yPerson.MiddleName, yPerson.Prefix, yPerson.Suffix });

            var firstAndMiddleNameCompareResult = defaultStringComparer.Compare(xFirstAndMiddleName, yFirstAndMiddleName);
            if (firstAndMiddleNameCompareResult != 0) return firstAndMiddleNameCompareResult;

            if (_cultureForSorting == CultureInfo.GetCultureInfo("de-DE"))
            {
                var lengthCompareResult = xFirstAndMiddleName.Length.CompareTo(yFirstAndMiddleName.Length);
                if (lengthCompareResult != 0) return lengthCompareResult;
            }

            return 0;


        }

19 Source : BSO007 Sort by first author and number of co-authors.cs
with MIT License
from Citavi

public int Compare(Citation x, Citation y)
        {
            /*
				This is an example of a custom sort macro that sorts all references of type 'internet doreplacedent' on top of the bibliography.
				The internet doreplacedents themselves are sorted according to a different logic than the rest of the cited doreplacedents.
				Return values:
				0:					x is considered the same as y sorting-wise, so we cannot tell a difference based on the algorithm below
				> 0 (positive):		x should go after y, x is greater than y
				< 0 (negative):		x should go before y, x is less than
			*/


            if (x == null || y == null) return 0;

            Reference xReference = x.Reference;
            Reference yReference = y.Reference;
            if (xReference == null || yReference == null) return 0;

            ReferenceType xReferenceType = xReference.ReferenceType;
            ReferenceType yReferenceType = yReference.ReferenceType;

            var xAuthors = xReference.AuthorsOrEditorsOrOrganizations;
            var yAuthors = yReference.AuthorsOrEditorsOrOrganizations;

            int xAuthorsCount = 0;
            int yAuthorsCount = 0;
            if (xAuthors != null) xAuthorsCount = xAuthors.Count;
            if (yAuthors != null) yAuthorsCount = yAuthors.Count;

            string xreplacedleForSorting = GetreplacedleForSorting(xReference);
            string yreplacedleForSorting = GetreplacedleForSorting(yReference);

            string xVolume = xReference.Volume;
            string yVolume = yReference.Volume;

            string xSeriesreplacedleForSorting = GetSeriesreplacedleForSorting(xReference);
            string ySeriesreplacedleForSorting = GetSeriesreplacedleForSorting(yReference);


            StringComparer defaultStringComparer = StringComparer.Create(_cultureForSorting, true);
            int authorCompareResult = 0;
            int authorsCountCompareResult = 0;
            int replacedleCompareResult = 0;
            int seriesreplacedleCompareResult = 0;
            int volumeCompareResult = 0;
            int yearCompareResult = 0;
            int editionCompareResult = 0;

            /*
				Die Werke werden in alphabetischer Reihenfolge nach den Familiennamen der Erstautoren bzw. -autorinnen gereiht.
				Ist bei einer Quelle kein Autor bzw. keine Autorin vorhanden, rückt der replacedel an die Stelle des Autorennamens und das Werk
				wird nach dem ersten Wort des replacedels (wobei bestimmte und unbestimmte Artikel unberücksichtigt bleiben) alphabetisch gereiht.
			*/


            if (xAuthorsCount == 0 && yAuthorsCount == 0)
            {
                //compare replacedles
                replacedleCompareResult = xreplacedleForSorting.CompareTo(yreplacedleForSorting);
                if (replacedleCompareResult != 0) return replacedleCompareResult;

                seriesreplacedleCompareResult = xSeriesreplacedleForSorting.CompareTo(ySeriesreplacedleForSorting);
                if (seriesreplacedleCompareResult != 0) return seriesreplacedleCompareResult;
            }
            else if (xAuthorsCount == 0 && yAuthorsCount > 0)
            {
                //compare xreplacedle with yFirstAuthor
                replacedleCompareResult = defaultStringComparer.Compare(xreplacedleForSorting, yAuthors.ElementAt(0).FullName);
                if (replacedleCompareResult != 0) return replacedleCompareResult;
            }
            else if (xAuthorsCount > 0 && yAuthorsCount == 0)
            {
                //compare xFirstAuthor with yreplacedle
                replacedleCompareResult = defaultStringComparer.Compare(xAuthors.ElementAt(0).FullName, yreplacedleForSorting);
                if (replacedleCompareResult != 0) return replacedleCompareResult;
            }
            else
            {
                int minAuthorCount = Math.Min(xAuthorsCount, yAuthorsCount);

                for (int i = 0; i < minAuthorCount; i++)
                {
                    authorCompareResult = CompareAuthors(xAuthors.ElementAt(i), yAuthors.ElementAt(i));
                    if (authorCompareResult != 0) return authorCompareResult;

                    authorsCountCompareResult = xAuthorsCount.CompareTo(yAuthorsCount);
                    if (authorsCountCompareResult != 0) return authorsCountCompareResult;
                }
            }


            /*
				Innerhalb der Gruppe chronologisch aufsteigend
			*/
            #region Year

            yearCompareResult = YearComparer.Compare(x, y);
            if (yearCompareResult != 0) return yearCompareResult;

            #endregion Year

            #region Volume

            if
            (
                xReferenceType == yReferenceType &&
                xReference.HasCoreField(ReferenceTypeCoreFieldId.Volume) &&
                yReference.HasCoreField(ReferenceTypeCoreFieldId.Volume)
            )
            {
                NumberStringComparer volumeComparer = new NumberStringComparer()
                {
                    CompareMode = NumberStringCompareMode.ByTextAndNumbersSegmentwise,
                    UseAbsoluteNumbersOnly = true
                };

                volumeCompareResult = volumeComparer.Compare(xVolume, yVolume);
                if (volumeCompareResult != 0) return volumeCompareResult;
            }

            #endregion Volume

            #region replacedle

            replacedleCompareResult = defaultStringComparer.Compare(xreplacedleForSorting, yreplacedleForSorting);
            if (replacedleCompareResult != 0) return replacedleCompareResult;


            #endregion replacedle

            #region Edition

            if
            (
                xReference.HasCoreField(ReferenceTypeCoreFieldId.Edition) &&
                yReference.HasCoreField(ReferenceTypeCoreFieldId.Edition)
            )
            {
                var xEdition = xReference.EditionNumberResolved;
                var yEdition = yReference.EditionNumberResolved;

                bool xHasEdition = !string.IsNullOrEmpty(xEdition);
                bool yHasEdition = !string.IsNullOrEmpty(yEdition);


                if (xHasEdition && yHasEdition)
                {
                    NumberStringComparer editionComparer = new NumberStringComparer()
                    {
                        CompareMode = NumberStringCompareMode.ByTextAndNumbersSegmentwise,
                        UseAbsoluteNumbersOnly = true
                    };

                    editionCompareResult = editionComparer.Compare(xEdition, yEdition);
                    if (editionCompareResult != 0) return editionCompareResult;
                }
                else if (xHasEdition && !yHasEdition) //y before x
                {
                    return 1;
                }
                else if (!xHasEdition && yHasEdition) //x before y
                {
                    return -1;
                }
            }

            #endregion

            return 0;
        }

19 Source : BSO007 Sort by first author and number of co-authors.cs
with MIT License
from Citavi

private int CompareAuthors(Person xAuthor, Person yAuthor)
        {
            if (xAuthor == null || yAuthor == null) return 0;

            StringComparer defaultStringComparer = StringComparer.Create(_cultureForSorting, true);

            var xLastNameForSortingResolved = xAuthor.GetLastNameForSortingResolved();
            var yLastNameForSortingResolved = yAuthor.GetLastNameForSortingResolved();

            //var lastNameCompareResult = xLastNameForSortingResolved.CompareTo(yLastNameForSortingResolved);
            var lastNameCompareResult = defaultStringComparer.Compare(xLastNameForSortingResolved, yLastNameForSortingResolved);
            if (lastNameCompareResult != 0) return lastNameCompareResult;

            if (_cultureForSorting == CultureInfo.GetCultureInfo("de-DE"))
            {
                var lengthCompareResult = xLastNameForSortingResolved.CompareTo(yLastNameForSortingResolved);
                if (lengthCompareResult != 0) return lengthCompareResult;
            }

            var xFirstAndMiddleName = ConcatNonEmptyStrings(" ", new string[] { xAuthor.FirstName, xAuthor.MiddleName, xAuthor.Prefix, xAuthor.Suffix });
            var yFirstAndMiddleName = ConcatNonEmptyStrings(" ", new string[] { xAuthor.FirstName, xAuthor.MiddleName, xAuthor.Prefix, xAuthor.Suffix });

            var firstAndMiddleNameCompareResult = defaultStringComparer.Compare(xFirstAndMiddleName, yFirstAndMiddleName);
            if (firstAndMiddleNameCompareResult != 0) return firstAndMiddleNameCompareResult;

            if (_cultureForSorting == CultureInfo.GetCultureInfo("de-DE"))
            {
                var lengthCompareResult = xFirstAndMiddleName.Length.CompareTo(yFirstAndMiddleName.Length);
                if (lengthCompareResult != 0) return lengthCompareResult;
            }

            return 0;


        }

19 Source : COT008_Convert_output_to_lower_case.cs
with MIT License
from Citavi

public IEnumerable<ITextUnit> GetTextUnits(ComponentPart componentPart, Template template, Citation citation, out bool handled)
		{


			var ensureEnglishIsReferenceLanguage = true;	//if set to false, the component part filter will ALWAYS capitalize, regardless of the reference's language
			var upperCaseAfterPunctuation = true;			//if set to false, everything but the very first word will be lower case
			var modeStrict = false;							//only applicable if ensureEnglishIsReferenceLanguage = true: 
															//if modeStrict = true, it will only capitalize references that have "en" or "eng" etc. in the language field
															//if modeStrict = false, it will also capitalize references that have an empty language field

			CultureInfo culture = CultureInfo.CurrentCulture;

			handled = false;

			if (citation == null) return null;
			if (citation.Reference == null) return null;
			if (componentPart == null) return null;
			if (template == null) return null;

			if (ensureEnglishIsReferenceLanguage)
			{
				string languageResolved = citation.Reference.Language;
				if (componentPart.Scope == ComponentPartScope.Reference)
				{
					//if ComponentPartScope is Reference, language can come from Reference or ParentReference
					if (string.IsNullOrEmpty(languageResolved) && citation.Reference.ParentReference != null)
					{
						languageResolved = citation.Reference.ParentReference.Language;
					}
					if (string.IsNullOrEmpty(languageResolved) && modeStrict) return null;
				}
				else
				{
					//if ComponentPartScope is ParentReference, language MUST come from ParentReference
					if (citation.Reference.ParentReference == null) return null;
					languageResolved = citation.Reference.ParentReference.Language;
				}
				if (string.IsNullOrEmpty(languageResolved) && modeStrict) return null;

				if (!string.IsNullOrEmpty(languageResolved))
				{
					var termsList = new string[] {
						"en",
						"eng",
						"engl",
						"English",
						"Englisch"
					};


					var regEx = new Regex(@"\b(" + string.Join("|", termsList) + @")\b", RegexOptions.IgnoreCase);
					if (!regEx.IsMatch(languageResolved))
					{
						return null;
					}
				}
			}	//


			var textUnits = componentPart.GetTextUnitsUnfiltered(citation, template);
			if (textUnits == null || !textUnits.Any()) return null;

			//Expressions that must not be changed with regards to capitalization
			List<string> printreplacedtatedExpressions = new List<string>()
			{
				"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", 
				"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December",
				"Austria", "Belgium", "Croatia", "Czech Republic", "Denmark", "Estonia", "Finland", "France", "Germany", "Greece", 
				"Great Britain", "Hungary", "Iceland", "Ireland", "Italy", "Latvia", "Liechtenstein", "Lithuania", "Luxembourg", "Malta", 
				"Netherlands", "Norway", "Poland", "Portugal", "Russia", "Slovakia", "Slovenia", "Spain", "Sweden", "Switzerland", "Turkey", 
				"United Kingdom", "UK", "European Union", "European", "United Nations", "UN", 
				"Canada", "Canadadian", "replacedan", "replacedanese", "US‐replacedanese", "U", "US", "USA", "United States of America", "American",
				"Amsterdam", "Brussels", "Cologne", "Columbia", "Den Haag", "London", "Moscow", "Munich", "Paris", "Vienna", "Zurich",
				"AG", "ARD", "ZDF", "GmbH", "WDR", "Amazon", "Google", "Microsoft", 
				"CEO", "CEOs", "CFO", "CSR", "DAX", "F&E", "I", "Inc", "Ltd", "MBA", "M&A", "M&As", "NASDAQ", "R&D", "VC", "VCs"
			};
			printreplacedtatedExpressions.Sort((x, y) => y.Length.CompareTo(x.Length)); //descending: longer ones first

			//Break the input text into a list of words at whitespaces,
			//hyphens, opening parens, and ASCII quotation marks
			//as well as the above printreplacedtatedExpressions
			string allInterpunctuation = @"(\s)|(-)|(\()|(\))|("")|(„)|(“)|(“)|(”)|(‘)|(’)|(«)|(»)|(\.)|(:)|(\?)|(!)";
			string splitPattern = printreplacedtatedExpressions.Count == 0 ?
				allInterpunctuation :
				string.Format(@"({0})", String.Join("|", printreplacedtatedExpressions.Select(x => string.Format(@"\b{0}\b", Regex.Escape(x))))) + "|" + allInterpunctuation;

			string interpunctuactionFollowedByCapitalization = @"(\.)|(:)|(\?)|(!)"; //next word will be capitalized if possible
			bool firstWordDone = false;

			for (int i = 0; i < textUnits.Count; i++)
			{
				//textUnit.Text = textUnits[i].Text.ToLower(culture);
				var text = textUnits[i].Text;

				List<string> words = Regex.Split(text, splitPattern, RegexOptions.IgnoreCase).Where(x => !string.IsNullOrEmpty(x)).ToList();

				text = string.Empty;

				for (int j = 0; j < words.Count; j++)
				{
					var word = words[j].ToString();

					if (Regex.IsMatch(word, allInterpunctuation) || word.Equals(" "))
					{
						//space or punctuation
						text = text + word;
						continue;
					}

					string printreplacedtatedExpression = printreplacedtatedExpressions.FirstOrDefault(ex => ex.Equals(word, StringComparison.OrdinalIgnoreCase));
					if (!string.IsNullOrEmpty(printreplacedtatedExpression))
					{
						text = text + printreplacedtatedExpression;
						firstWordDone = true;
						continue;
					}

					if (((i == 0) && (j == 0)) || !firstWordDone)
					{
						text = text + ToUpperFirstLetter(word, culture);
						firstWordDone = true;
					}
					else if (upperCaseAfterPunctuation && ((j > 0 && Regex.IsMatch(words[j - 1], interpunctuactionFollowedByCapitalization)) || (j > 1 && Regex.IsMatch(words[j - 2], interpunctuactionFollowedByCapitalization))))
					{
						text = text + ToUpperFirstLetter(word, culture);
						firstWordDone = true;
					}
					else
					{
						text = text + word.ToLower(culture);
						firstWordDone = true;
					}
				}
				textUnits[i].Text = text;
			}

			handled = true;
			return textUnits;
		}

19 Source : SpeedLimitManager.cs
with MIT License
from CitiesSkylinesMods

public override void OnBeforeLoadData() {
            base.OnBeforeLoadData();

#if DEBUG
            bool debugSpeedLimits = DebugSwitch.SpeedLimits.Get();
#endif

            // determine vanilla speed limits and customizable NetInfos
            SteamHelper.DLC_BitMask dlcMask =
                SteamHelper.GetOwnedDLCMask().IncludingMissingGameDlcBitmasks();

            int numLoaded = PrefabCollection<NetInfo>.LoadedCount();

            // todo: move this to a Reset() or Clear() method?
            vanillaLaneSpeedLimitsByNetInfoName_.Clear();
            customizableNetInfos_.Clear();
            customLaneSpeedLimitByNetInfoName_.Clear();
            childNetInfoNamesByCustomizableNetInfoName_.Clear();
            netInfoByName_.Clear();

            List<NetInfo> mainNetInfos = new List<NetInfo>();

            // Basic logging to help road/track replacedet creators see if their netinfo is wrong
            // 6000 is rougly 120 lines; should be more than enough for most users
            StringBuilder log = new StringBuilder(6000);

            log.AppendFormat(
                "SpeedLimitManager.OnBeforeLoadData: {0} NetInfos loaded. Verifying...\n",
                numLoaded);

            for (uint i = 0; i < numLoaded; ++i) {
                NetInfo info = PrefabCollection<NetInfo>.GetLoaded(i);

                // Basic validity checks to see if this NetInfo is something speed limits can be applied to...

                // Something in the workshop has null NetInfos in it...
                if (info == null) {
                    Log.InfoFormat(
                        "SpeedLimitManager.OnBeforeLoadData: NetInfo #{0} is null!",
                        i);
                    continue;
                }

                string infoName = info.name;

                // We need a valid name
                if (string.IsNullOrEmpty(infoName)) {
                    log.AppendFormat(
                        "- Skipped: NetInfo #{0} - name is empty!\n",
                        i);
                    continue;
                }

                // Make sure it's valid AI
                if (info.m_netAI == null) {
                    log.AppendFormat(
                        "- Skipped: NetInfo #{0} ({1}) - m_netAI is null.\n",
                        i,
                        infoName);
                    continue;
                }

                // Must be road or track based
                if (!(info.m_netAI is RoadBaseAI || info.m_netAI is TrainTrackBaseAI ||
                      info.m_netAI is MetroTrackAI)) {
#if DEBUG
                    // Only outputting these in debug as there are loads of them
                    Log._DebugIf(
                        debugSpeedLimits,
                        () =>
                            $"- Skipped: NetInfo #{i} ({infoName}) - m_netAI is not applicable: {info.m_netAI}.");
#endif
                    continue;
                }

                // If it requires DLC, check the DLC is active
                if ((info.m_dlcRequired & dlcMask) != info.m_dlcRequired) {
                    log.AppendFormat(
                        "- Skipped: NetInfo #{0} ({1}) - required DLC not active.\n",
                        i,
                        infoName);
                    continue;
                }

                // #510: Filter out decorative networks (`None`) and bike paths (`Bicycle`)
                if (info.m_vehicleTypes == VehicleInfo.VehicleType.None ||
                    info.m_vehicleTypes == VehicleInfo.VehicleType.Bicycle) {
                    log.AppendFormat(
                        "- Skipped: NetInfo #{0} ({1}) - no vehicle support (decorative or bike path?)\n",
                        i,
                        infoName);
                    continue;
                }

                if (!vanillaLaneSpeedLimitsByNetInfoName_.ContainsKey(infoName)) {
                    if (info.m_lanes == null) {
                        log.AppendFormat(
                            "- Skipped: NetInfo #{0} ({1}) - m_lanes is null!\n",
                            i,
                            infoName);

                        Log.Warning(
                            $"SpeedLimitManager.OnBeforeLoadData: NetInfo @ {i} ({infoName}) lanes is null!");
                        continue;
                    }

                    Log._Trace($"- Loaded road NetInfo: {infoName}");

                    netInfoByName_[infoName] = info;
                    mainNetInfos.Add(info);

                    float[] vanillaLaneSpeedLimits = new float[info.m_lanes.Length];

                    for (var k = 0; k < info.m_lanes.Length; ++k) {
                        vanillaLaneSpeedLimits[k] = info.m_lanes[k].m_speedLimit;
                    }

                    vanillaLaneSpeedLimitsByNetInfoName_[infoName] = vanillaLaneSpeedLimits;
                }
            }

            log.Append("SpeedLimitManager.OnBeforeLoadData: Scan complete.\n");
            Log.Info(log.ToString());

            mainNetInfos.Sort(
                (NetInfo a, NetInfo b) => {
                    // todo: move arrow function somewhere else?
                    bool aRoad = a.m_netAI is RoadBaseAI;
                    bool bRoad = b.m_netAI is RoadBaseAI;

                    if (aRoad != bRoad) {
                        return aRoad ? -1 : 1;
                    }

                    bool aTrain = a.m_netAI is TrainTrackBaseAI;
                    bool bTrain = b.m_netAI is TrainTrackBaseAI;

                    if (aTrain != bTrain) {
                        return aTrain ? 1 : -1;
                    }

                    bool aMetro = a.m_netAI is MetroTrackAI;
                    bool bMetro = b.m_netAI is MetroTrackAI;

                    if (aMetro != bMetro) {
                        return aMetro ? 1 : -1;
                    }

                    if (aRoad && bRoad) {
                        bool aHighway = ((RoadBaseAI)a.m_netAI).m_highwayRules;
                        bool bHighway = ((RoadBaseAI)b.m_netAI).m_highwayRules;

                        if (aHighway != bHighway) {
                            return aHighway ? 1 : -1;
                        }
                    }

                    int aNumVehicleLanes = 0;
                    foreach (NetInfo.Lane lane in a.m_lanes) {
                        if ((lane.m_laneType & LANE_TYPES) != NetInfo.LaneType.None) {
                            ++aNumVehicleLanes;
                        }
                    }

                    int bNumVehicleLanes = 0;
                    foreach (NetInfo.Lane lane in b.m_lanes) {
                        if ((lane.m_laneType & LANE_TYPES) != NetInfo.LaneType.None)
                            ++bNumVehicleLanes;
                    }

                    int res = aNumVehicleLanes.CompareTo(bNumVehicleLanes);
                    if (res == 0) {
                        return a.name.CompareTo(b.name);
                    } else {
                        return res;
                    }
                });

            // identify parent NetInfos
            int x = 0;
            while (x < mainNetInfos.Count) {
                NetInfo info = mainNetInfos[x];
                string infoName = info.name;

                // find parent with prefix name
                bool foundParent = false;
                foreach (NetInfo parentInfo in mainNetInfos) {
                    if (info.m_placementStyle == ItemClreplaced.Placement.Procedural
                        && !infoName.Equals(parentInfo.name)
                        && infoName.StartsWith(parentInfo.name)) {
                        Log._Trace(
                            $"Identified child NetInfo {infoName} of parent {parentInfo.name}");

                        if (!childNetInfoNamesByCustomizableNetInfoName_.TryGetValue(
                                parentInfo.name,
                                out List<string> childNetInfoNames)) {
                            childNetInfoNamesByCustomizableNetInfoName_[parentInfo.name] =
                                childNetInfoNames = new List<string>();
                        }

                        childNetInfoNames.Add(info.name);
                        netInfoByName_[infoName] = info;
                        foundParent = true;
                        break;
                    }
                }

                if (foundParent) {
                    mainNetInfos.RemoveAt(x);
                } else {
                    ++x;
                }
            }

            customizableNetInfos_ = mainNetInfos;
        }

19 Source : AnimationStateMachine.cs
with GNU General Public License v3.0
from cloudhu

public int Compare (int x, int y)
		{
			return( x.CompareTo( y ) * -1);
		}

19 Source : FoldersManagerForm.cs
with GNU General Public License v3.0
from ClusterM

public int Compare(object o1, object o2)
            {
                if (o1 is ListViewItem)
                    o1 = (o1 as ListViewItem).Tag;
                if (o2 is ListViewItem)
                    o2 = (o2 as ListViewItem).Tag;

                if ((o1 as TreeNode).Tag is NesMenuCollection) return -1; // Root is always first
                if ((o2 as TreeNode).Tag is NesMenuCollection) return 1;
                INesMenuElement el1 = (o1 as TreeNode).Tag as INesMenuElement;
                INesMenuElement el2 = (o2 as TreeNode).Tag as INesMenuElement;
                var pos1 = 2;
                var pos2 = 2;
                if (el1 is NesMenuFolder) pos1 = (int)(el1 as NesMenuFolder).Position;
                if (el2 is NesMenuFolder) pos2 = (int)(el2 as NesMenuFolder).Position;
                if (pos1 != pos2) return pos1.CompareTo(pos2);
                return el1.Name.CompareTo(el2.Name);
            }

19 Source : ObjectId.cs
with MIT License
from cocosip

public int CompareTo(ObjectId other)
        {
            int r = _timestamp.CompareTo(other._timestamp);
            if (r != 0) { return r; }
            r = _machine.CompareTo(other._machine);
            if (r != 0) { return r; }
            r = _pid.CompareTo(other._pid);
            if (r != 0) { return r; }
            return _increment.CompareTo(other._increment);
        }

19 Source : AddNodeStrategy.cs
with MIT License
from colgreen

public NeatGenome<T>? CreateChildGenome(NeatGenome<T> parent, IRandomSource rng)
        {
            if(parent.ConnectionGenes.Length == 0)
            {
                // No connections to split (nodes are added by splitting an existing connection).
                return null;
            }

            // Select a connection at random.
            int splitConnIdx = rng.Next(parent.ConnectionGenes.Length);
            var splitConn = parent.ConnectionGenes._connArr[splitConnIdx];

            // The selected connection will be replaced with a new node and two new connections;
            // get an innovation ID for the new node.
            int addedNodeId = GetInnovationID(splitConn, parent, out bool newInnovationIdsFlag);

            // Create the two new connections.
            var newConnArr = new DirectedConnection[] {
                new DirectedConnection(splitConn.SourceId, addedNodeId),
                new DirectedConnection(addedNodeId, splitConn.TargetId)
            };

            // Get weights for the new connections.
            // Connection 1 gets the weight from the original connection; connection 2 gets a fixed
            // weight of _metaNeatGenome.ConnectionWeightRange.

            // ENHANCEMENT: Consider a better choice of weights for the new connections; this scheme has been
            // copied from sharpneat 2.x as a starting point, but can likely be improved upon.
            var newWeightArr = new T[] {
                parent.ConnectionGenes._weightArr[splitConnIdx],
                (T)Convert.ChangeType(_metaNeatGenome.ConnectionWeightScale, typeof(T))
            };

            // Ensure newConnArr is sorted.
            // Later on we'll determine their insertion indexes into the connection array, therefore this ensures that
            // the insert indexes will be sorted correctly.
            if(newConnArr[0].CompareTo(newConnArr[1]) > 0)
            {
                var tmpConn = newConnArr[0];
                newConnArr[0] = newConnArr[1];
                newConnArr[1] = tmpConn;

                T tmpWeight = newWeightArr[0];
                newWeightArr[0] = newWeightArr[1];
                newWeightArr[1] = tmpWeight;
            }

            // Create a new connection gene array that consists of the parent connection genes,
            // with the connection that was split removed, and the two new connection genes that
            // replace it inserted at the correct (sorted) positions.
            var parentConnArr = parent.ConnectionGenes._connArr;
            var parentWeightArr = parent.ConnectionGenes._weightArr;
            int parentLen = parentConnArr.Length;

            // Create the child genome's ConnectionGenes object.
            int childLen = parentLen + 1;
            var connGenes = new ConnectionGenes<T>(childLen);
            var connArr = connGenes._connArr;
            var weightArr = connGenes._weightArr;

            // Build an array of parent indexes to stop at when copying from the parent to the child connection array.
            // Note. Each index is combined with a second value; an index into newConnArr for insertions,
            // and -1 for the split index (the connection to be removed)
            int insertIdx1 = ~Array.BinarySearch(parent.ConnectionGenes._connArr, newConnArr[0]);
            int insertIdx2 = ~Array.BinarySearch(parent.ConnectionGenes._connArr, newConnArr[1]);
            (int,int)[] stopIdxArr = new[]
            {
                (splitConnIdx, -1),
                (insertIdx1, 0),
                (insertIdx2, 1)
            };

            // Sort by the first index value.
            Array.Sort(stopIdxArr, ((int,int)x, (int,int)y) => x.Item1.CompareTo(y.Item1));

            // Loop over stopIdxArr.
            int parentIdx = 0;
            int childIdx = 0;

            for(int i=0; i < stopIdxArr.Length; i++)
            {
                int stopIdx = stopIdxArr[i].Item1;
                int newConIdx = stopIdxArr[i].Item2;

                // Copy all parent genes up to the stop index.
                int copyLen = stopIdx - parentIdx;
                if(copyLen > 0)
                {
                    Array.Copy(parentConnArr, parentIdx, connArr, childIdx, copyLen);
                    Array.Copy(parentWeightArr, parentIdx, weightArr, childIdx, copyLen);
                }

                // Update parentIdx, childIdx.
                parentIdx = stopIdx;
                childIdx += copyLen;

                // Test what to do at the stopIdx.
                if(newConIdx == -1)
                {   // We are at the parent connection to be skipped.
                    parentIdx++;
                    continue;
                }

                // We are at an insertion point in connArr.
                connArr[childIdx] = newConnArr[newConIdx];
                weightArr[childIdx] = newWeightArr[newConIdx];

                childIdx++;
            }

            // Copy any remaining connection genes.
            int len = parentConnArr.Length - parentIdx;
            if (len > 0)
            {
                Array.Copy(parentConnArr, parentIdx, connArr, childIdx, len);
                Array.Copy(parentWeightArr, parentIdx, weightArr, childIdx, len);
            }

            // Note. We can construct a NeatGenome without preplaceding the pre-built arrays connIdxArr and hiddenNodeIdArr;
            // however this way is more efficient. The downside is that the logic to pre-build these arrays is highly complex
            // and therefore difficult to understand, modify, and is thus a possible source of defects if modifications are attempted.

            // Create an array of hidden node IDs.
            var hiddenNodeIdArr = GetHiddenNodeIdArray(parent, addedNodeId, newInnovationIdsFlag);

            // Create and return a new genome.
            return _genomeBuilder.Create(
                _genomeIdSeq.Next(),
                _generationSeq.Peek,
                connGenes,
                hiddenNodeIdArr);
        }

19 Source : EnumerableExtensions.cs
with MIT License
from commandlineparser

private static IEnumerable<TSource> replacedertCountImpl<TSource>(IEnumerable<TSource> source,
            int count, Func<int, int, Exception> errorSelector)
        {
            var collection = source as ICollection<TSource>; // Optimization for collections
            if (collection != null)
            {
                if (collection.Count != count) {
                    throw errorSelector(collection.Count.CompareTo(count), count);
                }   
                return source;
            }

            return ExpectingCountYieldingImpl(source, count, errorSelector);
        }

19 Source : Fixed16Dot16.cs
with MIT License
from CommitteeOfZero

public int CompareTo(Fixed16Dot16 other) => Value.CompareTo(other.Value);

19 Source : Fixed26Dot6.cs
with MIT License
from CommitteeOfZero

public int CompareTo(Fixed26Dot6 other) => Value.CompareTo(other.Value);

19 Source : CompositionTimeDeltas.cs
with MIT License
from Const-me

int IComparer<IndexEntry>.Compare( IndexEntry x, IndexEntry y )
			{
				return x.offset.CompareTo( y.offset );
			}

19 Source : MessageFilterTable.cs
with MIT License
from CoreWCF

public int Compare(FilterTableEntry x, FilterTableEntry y)
            {
                // Highest priority first
                int p = y.priority.CompareTo(x.priority);
                if (p != 0)
                {
                    return p;
                }

                return x.table.GetType().FullName.CompareTo(y.table.GetType().FullName);
            }

19 Source : MessageFilterTable.cs
with MIT License
from CoreWCF

public bool Equals(FilterTableEntry x, FilterTableEntry y)
            {
                // Highest priority first
                int p = y.priority.CompareTo(x.priority);
                if (p != 0)
                {
                    return false;
                }

                return x.table.GetType().FullName.Equals(y.table.GetType().FullName);
            }

19 Source : ILOp.cs
with BSD 3-Clause "New" or "Revised" License
from CosmosOS

private static List<_FieldInfo> GetValueTypeFieldsInfo(Type type)
        {
            var structLayoutAttribute = type.StructLayoutAttribute;
            var fieldInfos = new List<_FieldInfo>();

            var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            switch (structLayoutAttribute.Value)
            {
                case LayoutKind.Auto:
                case LayoutKind.Sequential:
                    var offset = 0;
                    var pack = structLayoutAttribute.Pack;

                    if (pack == 0)
                    {
                        pack = (int)SizeOfType(typeof(IntPtr));
                    }

                    if (fields.Length > 0)
                    {
                        var typeAlignment = Math.Min(pack, fields.Max(f => SizeOfType(f.FieldType)));

                        Array.Sort(fields, (x, y) => x.MetadataToken.CompareTo(y.MetadataToken));

                        foreach (var field in fields)
                        {
                            var fieldSize = SizeOfType(field.FieldType);

                            var fieldAlignment = Math.Min(typeAlignment, fieldSize);
                            offset = (int)Align((uint)offset, (uint)fieldAlignment);

                            var fieldInfo = new _FieldInfo(
                                field.GetFullName(), SizeOfType(field.FieldType), type, field.FieldType);
                            fieldInfo.Offset = (uint)offset;
                            fieldInfo.Field = field;

                            fieldInfos.Add(fieldInfo);

                            offset += (int)fieldSize;
                        }
                    }

                    break;
                case LayoutKind.Explicit:
                    foreach (var field in fields)
                    {
                        var fieldInfo = new _FieldInfo(field.GetFullName(), SizeOfType(field.FieldType), type, field.FieldType);
                        fieldInfo.Offset = (uint)(field.GetCustomAttribute<FieldOffsetAttribute>()?.Value ?? 0);
                        fieldInfo.Field = field;

                        fieldInfos.Add(fieldInfo);
                    }

                    break;
                default:
                    throw new NotSupportedException();
            }

            return fieldInfos;
        }

19 Source : Cell.cs
with GNU General Public License v3.0
from Cr33zz

public int Compare(Cell x, Cell y)
            {
                return x.GlobalId.CompareTo(y.GlobalId);
            }

19 Source : RectanglePacker.cs
with MIT License
from cr4yz

public int CompareTo( Node other )
            {
                var wComparison = MaxSide.CompareTo( other.MaxSide );
                return wComparison != 0 ? wComparison : MinSide.CompareTo( other.H );
            }

19 Source : System_Int32_Binding.cs
with MIT License
from CragonGame

static StackObject* CompareTo_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject* ptr_of_this_method;
            StackObject* __ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Int32 @value = ptr_of_this_method->Value;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Int32 instance_of_this_method = GetInstance(__domain, ptr_of_this_method, __mStack);

            var result_of_this_method = instance_of_this_method.CompareTo(@value);

            __ret->ObjectType = ObjectTypes.Integer;
            __ret->Value = result_of_this_method;
            return __ret + 1;
        }

19 Source : MiscellaneousUtils.cs
with MIT License
from CragonGame

public static int ByteArrayCompare(byte[] a1, byte[] a2)
    {
      int lengthCompare = a1.Length.CompareTo(a2.Length);
      if (lengthCompare != 0)
        return lengthCompare;

      for (int i = 0; i < a1.Length; i++)
      {
        int valueCompare = a1[i].CompareTo(a2[i]);
        if (valueCompare != 0)
          return valueCompare;
      }

      return 0;
    }

19 Source : CardTypeHelperTexas.cs
with MIT License
from CragonGame

public static HandRankTypeTexasH GetHandRankHTexas(List<Card> cards)
        {
            HandRankTypeTexasH rank_type = HandRankTypeTexasH.HighCard;
            var hand_type = HandEvaluator.GetBestHand(cards).RankType;
            if (hand_type == HandRankTypeTexas.StraightFlush)
            {
                cards.Sort((card1, card2) =>
                {
                    return -((int)card1.Type).CompareTo((int)card2.Type);
                });

                if (cards[0].Type == (byte)CardType.Ace && cards[1].Type == (byte)CardType.King)
                {
                    rank_type = HandRankTypeTexasH.RoyalFlush;
                }
                else
                {
                    rank_type = HandRankTypeTexasH.StraightFlush;
                }
            }
            else
            {
                foreach (HandRankTypeTexasH i in Enum.GetValues(typeof(HandRankTypeTexasH)))
                {
                    HandRankTypeTexasH type = i;
                    if (type.ToString().Equals(hand_type.ToString()))
                    {
                        rank_type = type;
                        break;
                    }
                }
            }

            return rank_type;
        }

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

public int Compare(object x, object y)
        {
            return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y));
        }

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

public int Compare(IValueEquatable x, IValueEquatable y)
        {
            return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y));
        }

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

public int Compare(IEnumerable x, IEnumerable y)
        {
            return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y));
        }

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

public int Compare(IDictionary x, IDictionary y)
        {
            return ReferenceEquals(x, y) ? 0 : GetHashCode(x).CompareTo(GetHashCode(y));
        }

19 Source : LeapProjectChecks.cs
with MIT License
from crookookoo

private static void ensureChecksLoaded() {
      if (_projectChecks != null) {
        return;
      }

      _projectChecks = new List<ProjectCheck>();

      var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
      foreach (var type in replacedemblies.Query().SelectMany(a => a.GetTypes())) {
        foreach (var method in type.GetMethods(BindingFlags.Public
                                               | BindingFlags.NonPublic
                                               | BindingFlags.Static)) {
          var attributes = method.GetCustomAttributes(typeof(LeapProjectCheckAttribute),
                                                      inherit: true);
          if (attributes.Length == 0) {
            continue;
          }

          var attribute = attributes[0] as LeapProjectCheckAttribute;
          _projectChecks.Add(new ProjectCheck() {
            checkFunc = () => {
              if (!method.IsStatic) {
                Debug.LogError("Invalid project check definition; project checks must "
                             + "be static methods.");
                return true;
              }
              else if (method.ReturnType == typeof(bool)) {
                return (bool)method.Invoke(null, null);
              }
              else {
                return true;
              }
            },
            attribute = attribute
          });
        }
      }

      _projectChecks.Sort((a, b) => a.attribute.order.CompareTo(b.attribute.order));
    }

19 Source : JsonDiffPatch.cs
with Apache License 2.0
from cs-util-com

private JArray ArrayPatch(JArray left, JObject patch)
		{
			var toRemove = new List<JProperty>();
			var toInsert = new List<JProperty>();
			var toModify = new List<JProperty>();

			foreach (JProperty op in patch.Properties())
			{
				if (op.Name == "_t")
					continue;

				var value = op.Value as JArray;

				if (op.Name.StartsWith("_"))
				{
					// removed item from original array
					if (value != null && value.Count == 3 && (value[2].ToObject<int>() == (int)DiffOperation.Deleted || value[2].ToObject<int>() == (int)DiffOperation.ArrayMove))
					{
						toRemove.Add(new JProperty(op.Name.Substring(1), op.Value));

						if (value[2].ToObject<int>() == (int)DiffOperation.ArrayMove)
							toInsert.Add(new JProperty(value[1].ToObject<int>().ToString(), new JArray(left[int.Parse(op.Name.Substring(1))].DeepClone())));
					}
					else
					{
						throw new Exception($"Only removal or move can be applied at original array indices. Context: {value}");
					}
				}
				else
				{
					if (value != null && value.Count == 1)
					{
						toInsert.Add(op);
					}
					else
					{
						toModify.Add(op);
					}
				}
			}


			// remove items, in reverse order to avoid sawing our own floor
			toRemove.Sort((x, y) => int.Parse(x.Name).CompareTo(int.Parse(y.Name)));
			for (int i = toRemove.Count - 1; i >= 0; --i)
			{
				JProperty op = toRemove[i];
				left.RemoveAt(int.Parse(op.Name));
			}

			// insert items, in reverse order to avoid moving our own floor
			toInsert.Sort((x, y) => int.Parse(y.Name).CompareTo(int.Parse(x.Name)));
			for (int i = toInsert.Count - 1; i >= 0; --i)
			{
				JProperty op = toInsert[i];
				left.Insert(int.Parse(op.Name), ((JArray)op.Value)[0]);
			}

			foreach (var op in toModify)
			{
				JToken p = Patch(left[int.Parse(op.Name)], op.Value);
				left[int.Parse(op.Name)] = p;
			}

			return left;
		}

19 Source : JsonDiffPatch.cs
with Apache License 2.0
from cs-util-com

private JArray ArrayUnpatch(JArray right, JObject patch)
		{
			var toRemove = new List<JProperty>();
			var toInsert = new List<JProperty>();
			var toModify = new List<JProperty>();

			foreach (JProperty op in patch.Properties())
			{
				if (op.Name == "_t")
					continue;

				var value = op.Value as JArray;

				if (op.Name.StartsWith("_"))
				{
					// removed item from original array
					if (value != null && value.Count == 3 && (value[2].ToObject<int>() == (int)DiffOperation.Deleted || value[2].ToObject<int>() == (int)DiffOperation.ArrayMove))
					{
						var newOp = new JProperty(value[1].ToObject<int>().ToString(), op.Value);

						if (value[2].ToObject<int>() == (int)DiffOperation.ArrayMove)
						{
							toInsert.Add(new JProperty(op.Name.Substring(1), new JArray(right[value[1].ToObject<int>()].DeepClone())));
							toRemove.Add(newOp);
						}
						else
						{
							toInsert.Add(new JProperty(op.Name.Substring(1), new JArray(value[0])));
						}
					}
					else
					{
						throw new Exception($"Only removal or move can be applied at original array indices. Context: {value}");
					}
				}
				else
				{
					if (value != null && value.Count == 1)
					{
						toRemove.Add(op);
					}
					else
					{
						toModify.Add(op);
					}
				}
			}

			// first modify entries
			foreach (var op in toModify)
			{
				JToken p = Unpatch(right[int.Parse(op.Name)], op.Value);
				right[int.Parse(op.Name)] = p;
			}

			// remove items, in reverse order to avoid sawing our own floor
			toRemove.Sort((x, y) => int.Parse(x.Name).CompareTo(int.Parse(y.Name)));
			for (int i = toRemove.Count - 1; i >= 0; --i)
			{
				JProperty op = toRemove[i];
				right.RemoveAt(int.Parse(op.Name));
			}

			// insert items, in reverse order to avoid moving our own floor
			toInsert.Sort((x, y) => int.Parse(x.Name).CompareTo(int.Parse(y.Name)));
			foreach (var op in toInsert)
			{
				right.Insert(int.Parse(op.Name), ((JArray)op.Value)[0]);
			}

			return right;
		}

19 Source : BsonValue.cs
with Apache License 2.0
from cs-util-com

public virtual int CompareTo(BsonValue other, Collation collation)
        {
            // first, test if types are different
            if (this.Type != other.Type)
            {
                // if both values are number, convert them to Decimal (128 bits) to compare
                // it's the slowest way, but more secure
                if (this.IsNumber && other.IsNumber)
                {
                    return Convert.ToDecimal(this.RawValue).CompareTo(Convert.ToDecimal(other.RawValue));
                }
                // if not, order by sort type order
                else
                {
                    return this.Type.CompareTo(other.Type);
                }
            }

            // for both values with same data type just compare
            switch (this.Type)
            {
                case BsonType.Null:
                case BsonType.MinValue:
                case BsonType.MaxValue:
                    return 0;

                case BsonType.Int32: return this.AsInt32.CompareTo(other.AsInt32);
                case BsonType.Int64: return this.AsInt64.CompareTo(other.AsInt64);
                case BsonType.Double: return this.AsDouble.CompareTo(other.AsDouble);
                case BsonType.Decimal: return this.AsDecimal.CompareTo(other.AsDecimal);

                case BsonType.String: return collation.Compare(this.replacedtring, other.replacedtring);

                case BsonType.Doreplacedent: return this.AsDoreplacedent.CompareTo(other);
                case BsonType.Array: return this.AsArray.CompareTo(other);

                case BsonType.Binary: return this.AsBinary.BinaryCompareTo(other.AsBinary);
                case BsonType.ObjectId: return this.AsObjectId.CompareTo(other.AsObjectId);
                case BsonType.Guid: return this.AsGuid.CompareTo(other.AsGuid);

                case BsonType.Boolean: return this.AsBoolean.CompareTo(other.AsBoolean);
                case BsonType.DateTime:
                    var d0 = this.AsDateTime;
                    var d1 = other.AsDateTime;
                    if (d0.Kind != DateTimeKind.Utc) d0 = d0.ToUniversalTime();
                    if (d1.Kind != DateTimeKind.Utc) d1 = d1.ToUniversalTime();
                    return d0.CompareTo(d1);

                default: throw new NotImplementedException();
            }
        }

19 Source : ObjectId.cs
with Apache License 2.0
from cs-util-com

public int CompareTo(ObjectId other)
        {
            var r = this.Timestamp.CompareTo(other.Timestamp);
            if (r != 0) return r;

            r = this.Machine.CompareTo(other.Machine);
            if (r != 0) return r;

            r = this.Pid.CompareTo(other.Pid);
            if (r != 0) return r < 0 ? -1 : 1;

            return this.Increment.CompareTo(other.Increment);
        }

See More Examples