System.IComparable.CompareTo(object)

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

558 Examples 7

19 Source : DataChangedBehavior.cs
with MIT License
from 1iveowl

private static bool EvaluateComparable(IComparable leftOperand, ComparisonCondition operatorType, IComparable rightOperand)
        {
            object convertedOperand = null;
            try
            {
                convertedOperand = Convert.ChangeType(rightOperand, leftOperand.GetType(), CultureInfo.CurrentCulture);
            }
            catch (FormatException)
            {
            }
            catch (InvalidCastException)
            {
            }

            if (convertedOperand == null)
            {
                return operatorType == ComparisonCondition.NotEqual;
            }

            var comparison = leftOperand.CompareTo((IComparable)convertedOperand);
            switch (operatorType)
            {
                case ComparisonCondition.Equal:
                    return comparison == 0;
                case ComparisonCondition.NotEqual:
                    return comparison != 0;
                case ComparisonCondition.LessThan:
                    return comparison < 0;
                case ComparisonCondition.LessThanOrEqual:
                    return comparison <= 0;
                case ComparisonCondition.GreaterThan:
                    return comparison > 0;
                case ComparisonCondition.GreaterThanOrEqual:
                    return comparison >= 0;
                default:
                    return false;
            }
        }

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

private bool CheckVisibleRange(IComparable min, IComparable max)
        {
            return min.CompareTo(max) < 0;
        }

19 Source : YPeakViewportManager.cs
with MIT License
from ABTSoftware

protected override IRange OnCalculateNewYRange(IAxis yAxis, RenderPreplacedInfo renderPreplacedInfo)
        {
            var range = base.OnCalculateNewYRange(yAxis, renderPreplacedInfo);

            var min = FindMin(renderPreplacedInfo.DataSeries);
            var max = FindMax(renderPreplacedInfo.DataSeries);

            if(min == null || max == null) return range;

            if (IsNullOrInfinity(_min) || _min.CompareTo(min) > 0)
            {
                _min = min;
            }

            if (IsNullOrInfinity(_max) || _max.CompareTo(max) < 0)
            {
                _max = max;
            }

            range.Min = _min;
            range.Max = _max;

            return range;
        }

19 Source : AssertThat.cs
with MIT License
from AdemCatamak

public static void GreaterThan<T>(T minValue, T actual, string? message = null)
            where T : IComparable
        {
            if (actual.CompareTo(minValue) > 0)
            {
                return;
            }

            string exceptionMessage = message ?? $"Threshold : {minValue} -- Actual : {actual}";
            throw new replacedertGreaterThanException(exceptionMessage);
        }

19 Source : AssertThat.cs
with MIT License
from AdemCatamak

public static void LessThan<T>(T maxValue, T actual, string? message = null)
            where T : IComparable
        {
            if (actual.CompareTo(maxValue) < 0)
            {
                return;
            }

            string exceptionMessage = message ?? $"Threshold : {maxValue} -- Actual : {actual}";
            throw new replacedertLessThanException(exceptionMessage);
        }

19 Source : Expression.cs
with MIT License
from Adoxio

private static int Compare(object left, object right)
		{
			if (left == null && right == null) return 0;

			if (left is IComparable) return (left as IComparable).CompareTo(right);
			if (right is IComparable) return (right as IComparable).CompareTo(left) * -1;

			throw new InvalidOperationException(string.Format("The value {0} can't be compared to the value {1}.", left, right));
		}

19 Source : Converters.cs
with MIT License
from adrianmteo

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is IComparable a && parameter is IComparable b)
            {
                return a.CompareTo(b) >= 0;
            }

            return Visibility.Collapsed;
        }

19 Source : AduNumericUpDown.cs
with GNU General Public License v3.0
from aduskin

private bool IsLowerThan(T value1, T value2)
        {
            return value1.CompareTo(value2) < 0;
        }

19 Source : AduNumericUpDown.cs
with GNU General Public License v3.0
from aduskin

private bool IsLagerThan(T value1, T value2)
        {
            return value1.CompareTo(value2) > 0;
        }

19 Source : EnumerableExtensions.cs
with GNU Affero General Public License v3.0
from akira0245

public static TSource MaxElement<TSource, R>(this IEnumerable<TSource> container, Func<TSource, R> valuingFoo) where R : IComparable
    {
        var enumerator = container.GetEnumerator();
        if (!enumerator.MoveNext())
            throw new ArgumentException("Container is empty!");

        var maxElem = enumerator.Current;
        var maxVal = valuingFoo(maxElem);

        while (enumerator.MoveNext())
        {
            var currVal = valuingFoo(enumerator.Current);

            if (currVal.CompareTo(maxVal) > 0)
            {
                maxVal = currVal;
                maxElem = enumerator.Current;
            }
        }

        return maxElem;
    }

19 Source : EnumerableExtensions.cs
with GNU Affero General Public License v3.0
from akira0245

public static TSource MinElement<TSource, R>(this IEnumerable<TSource> container, Func<TSource, R> valuingFoo) where R : IComparable
    {
        var enumerator = container.GetEnumerator();
        if (!enumerator.MoveNext())
            throw new ArgumentException("Container is empty!");

        var maxElem = enumerator.Current;
        var maxVal = valuingFoo(maxElem);

        while (enumerator.MoveNext())
        {
            var currVal = valuingFoo(enumerator.Current);

            if (currVal.CompareTo(maxVal) < 0)
            {
                maxVal = currVal;
                maxElem = enumerator.Current;
            }
        }

        return maxElem;
    }

19 Source : EditableIf.cs
with MIT License
from alexismorin

protected bool Check( object LHS, ComparisonOperators op, object RHS )
	{
		if( !( LHS is IComparable ) || !( RHS is IComparable ) )
			throw new Exception( "Check using non basic type" );

		switch( op )
		{
			case ComparisonOperators.EqualTo:
			return ( (IComparable)LHS ).CompareTo( RHS ) == 0;

			case ComparisonOperators.NotEqualTo:
			return ( (IComparable)LHS ).CompareTo( RHS ) != 0;

			case ComparisonOperators.EqualsOrGreaterThan:
			return ( (IComparable)LHS ).CompareTo( RHS ) >= 0;

			case ComparisonOperators.EqualsOrLessThan:
			return ( (IComparable)LHS ).CompareTo( RHS ) <= 0;

			case ComparisonOperators.GreaterThan:
			return ( (IComparable)LHS ).CompareTo( RHS ) > 0;

			case ComparisonOperators.LessThan:
			return ( (IComparable)LHS ).CompareTo( RHS ) < 0;
			case ComparisonOperators.ContainsFlags:
			return ( (int)LHS & (int)RHS ) != 0; // Dont trust LHS values, it has been casted to a char and then to an int again, first bit will be the sign
			case ComparisonOperators.DoesNotContainsFlags:
			return ( ( (int)LHS & (int)RHS ) == (int)LHS ); // Dont trust LHS values, it has been casted to a char and then to an int again, first bit will be the sign

			default:
			break;
		}
		return false;
	}

19 Source : Attributes.cs
with Apache License 2.0
from Algoryx

public bool IsValid( object value )
    {
      Type type = value.GetType();
      if ( type == typeof( Vector4 ) )
        return IsValid( (Vector4)value );
      else if ( type == typeof( Vector3 ) )
        return IsValid( (Vector3)value );
      else if ( type == typeof( Vector2 ) )
        return IsValid( (Vector2)value );
      else if ( type == typeof( DefaultAndUserValueFloat ) ) {
        DefaultAndUserValueFloat val = (DefaultAndUserValueFloat)value;
        return val.Value > 0 || ( m_acceptZero && val.Value == 0 );
      }
      else if ( type == typeof( DefaultAndUserValueVector3 ) ) {
        DefaultAndUserValueVector3 val = (DefaultAndUserValueVector3)value;
        return IsValid( (Vector3)val.Value );
      }
      else if ( type == typeof( int ) )
        return (int)value > 0 || ( m_acceptZero && (int)value == 0 );
      else if ( value is IComparable ) {
        int returnCheck = m_acceptZero ? -1 : 0;
        // CompareTo returns 0 if the values are equal.
        return ( value as IComparable ).CompareTo( 0.0f ) > returnCheck;
      }
      else if ( type == typeof( float ) )
        return (float)value > 0 || ( m_acceptZero && (float)value == 0 );
      else if ( type == typeof( double ) )
        return (double)value > 0 || ( m_acceptZero && (double)value == 0 );
      return true;
    }

19 Source : Style.cs
with MIT License
from AliFlux

private bool validateUsingFilter(object[] filterArray, Dictionary<string, object> attributes)
        {
            if (filterArray.Count() == 0)
            {
            }
            var operation = filterArray[0] as string;
            bool result;

            if (operation == "all")
            {
                foreach (object[] subFilter in filterArray.Skip(1))
                {
                    if (!validateUsingFilter(subFilter, attributes))
                    {
                        return false;
                    }
                }
                return true;
            }
            else if (operation == "any")
            {
                foreach (object[] subFilter in filterArray.Skip(1))
                {
                    if (validateUsingFilter(subFilter, attributes))
                    {
                        return true;
                    }
                }
                return false;
            }
            else if (operation == "none")
            {
                result = false;
                foreach (object[] subFilter in filterArray.Skip(1))
                {
                    if (validateUsingFilter(subFilter, attributes))
                    {
                        result = true;
                    }
                }
                return !result;
            }

            switch (operation)
            {
                case "==":
                case "!=":
                case ">":
                case ">=":
                case "<":
                case "<=":

                    var key = (string)filterArray[1];

                    if (operation == "==")
                    {
                        if (!attributes.ContainsKey(key))
                        {
                            return false;
                        }
                    }
                    else
                    {
                        // special case, comparing inequality with non existent attribute
                        if (!attributes.ContainsKey(key))
                        {
                            return true;
                        }
                    }

                    if (!(attributes[key] is IComparable))
                    {
                        throw new NotImplementedException("Comparing colors probably");
                        return false;
                    }

                    var valueA = (IComparable)attributes[key];
                    var valueB = getValue(filterArray[2], attributes);

                    if (isNumber(valueA) && isNumber(valueB))
                    {
                        valueA = Convert.ToDouble(valueA);
                        valueB = Convert.ToDouble(valueB);
                    }

                    if (key is string)
                    {
                        if (key == "capital")
                        {

                        }
                    }

                    if (valueA.GetType() != valueB.GetType())
                    {
                        return false;
                    }

                    var comparison = valueA.CompareTo(valueB);

                    if (operation == "==")
                    {
                        return comparison == 0;
                    }
                    else if (operation == "!=")
                    {
                        return comparison != 0;
                    }
                    else if (operation == ">")
                    {
                        return comparison > 0;
                    }
                    else if (operation == "<")
                    {
                        return comparison < 0;
                    }
                    else if (operation == ">=")
                    {
                        return comparison >= 0;
                    }
                    else if (operation == "<=")
                    {
                        return comparison <= 0;
                    }

                    break;
            }

            if (operation == "has")
            {
                return attributes.ContainsKey(filterArray[1] as string);
            }
            else if (operation == "!has")
            {
                return !attributes.ContainsKey(filterArray[1] as string);
            }


            if (operation == "in")
            {
                var key = filterArray[1] as string;
                if (!attributes.ContainsKey(key))
                {
                    return false;
                }

                var value = attributes[key];

                foreach (object item in filterArray.Skip(2))
                {
                    if (getValue(item, attributes).Equals(value))
                    {
                        return true;
                    }
                }
                return false;
            }
            else if (operation == "!in")
            {
                var key = filterArray[1] as string;
                if (!attributes.ContainsKey(key))
                {
                    return true;
                }

                var value = attributes[key];

                foreach (object item in filterArray.Skip(2))
                {
                    if (getValue(item, attributes).Equals(value))
                    {
                        return false;
                    }
                }
                return true;
            }

            return false;
        }

19 Source : ObjectIsExtensions.cs
with MIT License
from aljazsim

public static bool IsEqualTo<T>(this T value1, T value2) where T : IComparable
        {
            if (!typeof(T).IsValueType)
            {
                if (value1 == null &&
                    value2 == null)
                {
                    return true;
                }
                else if (value1 != null &&
                         value2 != null)
                {
                    return value1.CompareTo(value2) == 0;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return value1.CompareTo(value2) == 0;
            }
        }

19 Source : ObjectIsExtensions.cs
with MIT License
from aljazsim

public static bool IsGreaterThan<T>(this T value, T minValue) where T : IComparable
        {
            if (!typeof(T).IsValueType)
            {
                ((object)value).CannotBeNull();
                ((object)minValue).CannotBeNull();
            }

            return value.CompareTo(minValue) > 0;
        }

19 Source : ObjectIsExtensions.cs
with MIT License
from aljazsim

public static bool IsGreaterThanOrEqualTo<T>(this T value, T minValue) where T : IComparable
        {
            if (!typeof(T).IsValueType)
            {
                ((object)value).CannotBeNull();
                ((object)minValue).CannotBeNull();
            }

            return value.CompareTo(minValue) >= 0;
        }

19 Source : ObjectIsExtensions.cs
with MIT License
from aljazsim

public static bool IsLessThan<T>(this T value, T maxValue) where T : IComparable
        {
            if (!typeof(T).IsValueType)
            {
                ((object)value).CannotBeNull();
                ((object)maxValue).CannotBeNull();
            }

            return value.CompareTo(maxValue) < 0;
        }

19 Source : ObjectIsExtensions.cs
with MIT License
from aljazsim

public static bool IsLessThanOrEqualTo<T>(this T value, T maxValue) where T : IComparable
        {
            if (!typeof(T).IsValueType)
            {
                ((object)value).CannotBeNull();
                ((object)maxValue).CannotBeNull();
            }

            return value.CompareTo(maxValue) <= 0;
        }

19 Source : ControlPanel.cs
with MIT License
from AmigoCap

bool CheckJsonData(JsonData data) { //Fixes potential errors in the .json (ensures end > start, n_ values positive, etc.)

            if (data.severalFiles_splitInstants) {
                if (data.pathAttributeUsedAs_n_atoms != "") {
                    MakeErrorWindow("Uncommon non-empty n_atom path attribute for a split-file dataset, please use splitInstants_instantsPerFile instead");
                    return false;
                }
            }
            else {
                string filename = Tools.GetFullPath(data.filename);
                if (!File.Exists(filename)) {
                    MakeErrorWindow("Data file not found at " + filename);
                    return false;
                }
            }


            void CheckValue<T>(ref T value, bool condition, T defaultvalue, string log) {
                if (condition) {
                    MakeWarningWindow(log + "\nReplacing with " + defaultvalue.ToString());
                    value = defaultvalue;
                }
            }

            void CheckValues_swap<T>(ref T lowValue, ref T highValue, string log) where T : System.IComparable {
                if (lowValue.CompareTo(highValue) > 0) {
                    T temp = lowValue;
                    lowValue = highValue;
                    highValue = temp;
                    MakeWarningWindow(log + "\nSwapping the two values.");
                }
            }

            CheckValue(ref data.districtSize.x, data.districtSize.x <= 0, 20, "Negative X value in District Size");
            CheckValue(ref data.districtSize.y, data.districtSize.y <= 0, 20, "Negative Y value in District Size");
            CheckValue(ref data.districtSize.z, data.districtSize.z <= 0, 20, "Negative Z value in District Size");

            if (data.lowerTruncature.x > data.upperTruncature.x ||
                data.lowerTruncature.y > data.upperTruncature.y ||
                data.lowerTruncature.z > data.upperTruncature.z) {
                MakeWarningWindow("lowerTruncature is not strictly inferior to upperTruncature, resetting to default values");
                data.lowerTruncature = new ControlPanel.JsonData.Vector3D { x = -1000, y = -1000, z = -1000 };
                data.upperTruncature = new ControlPanel.JsonData.Vector3D { x = 1000, y = 1000, z = 1000 };
            }

            if (data.dataset_n_paths <= 0) {
                MakeErrorWindow("Negative number of paths");
                return false;
            }
            if (!data.allPaths) {
                CheckValue(ref data.chosen_paths_start, data.chosen_paths_start < 0, 0, "Negative value for chosen_paths_start");
                CheckValue(ref data.chosen_paths_start, data.chosen_paths_start > data.dataset_n_paths, 0, "Chosen_paths_start value bigger than number of paths");

                CheckValue(ref data.chosen_paths_end, data.chosen_paths_end < 0, 500, "Negative value for chosen_paths_end");
                CheckValue(ref data.chosen_paths_end, data.chosen_paths_end > data.dataset_n_paths, 500, "Chosen paths end bigger than number of paths");

                CheckValues_swap(ref data.chosen_paths_start, ref data.chosen_paths_end, "Chosen paths start bigger than end");

                CheckValue(ref data.chosen_paths_step, data.chosen_paths_step < 1, 1, "Incorrect value for chosen_paths_step");

                if (data.randomPaths) {
                    CheckValue(ref data.chosen_n_paths, data.chosen_n_paths <= 0, 500, "Negative value for chosen_n_paths");
                    CheckValue(ref data.chosen_n_paths, data.chosen_n_paths > data.dataset_n_paths, 500, "Chosen_n_paths value bigger than number of paths");
                    if (data.chosen_n_paths >= data.chosen_paths_end - data.chosen_paths_start) {
                        MakeWarningWindow("Asking for more random paths than the range allows; Falling back to non-random paths in specified range");
                        data.randomPaths = false;
                        data.chosen_n_paths = data.chosen_paths_end - data.chosen_paths_start;
                        data.chosen_paths_step = 1;
                    }
                }
            }

            //constant_n_instants

            if (data.dataset_n_instants <= 0) {
                MakeErrorWindow("Negative number of instants");
                return false;
            }
            if (!data.allInstants) {
                CheckValue(ref data.chosen_instants_start, data.chosen_instants_start < 0, 0, "Negative value for chosen_instants_start");
                CheckValue(ref data.chosen_instants_start, data.chosen_instants_start > data.dataset_n_instants, 0, "Chosen_instants_start value bigger than number of instants");

                CheckValue(ref data.chosen_instants_end, data.chosen_instants_end < 0, data.dataset_n_instants, "Negative value for chosen_instants_end");
                CheckValue(ref data.chosen_instants_end, data.chosen_instants_end > data.dataset_n_instants, data.dataset_n_instants, "Chosen instants end bigger than number of instants");

                if (data.chosen_instants_start > data.chosen_instants_end) {
                    int temp = data.chosen_instants_end;
                    data.chosen_instants_end = data.chosen_instants_start;
                    data.chosen_instants_start = temp;
                }

                CheckValue(ref data.chosen_instants_step, data.chosen_instants_step < 1, 1, "Incorrect value for chosen_instants_step");
            }

            if (data.useGPSCoords) {
                CheckValue(ref data.GPSOrigin.x, Mathf.Abs(data.GPSOrigin.x) > 90, 0, "lareplacedude in decimal degree out of range +-90°");
                CheckValue(ref data.GPSOrigin.y, Mathf.Abs(data.GPSOrigin.y) > 180, 0, "longitude in decimal degree out of range +-180°");
            }

            CheckValue(ref data.spheresRadius, data.spheresRadius < 0, 2, "Negative Value for spheresRadius");
            //spheresAnimSpeed --> can be negative
            // spheresGlobalTime --> can either be negative or positive
            // spheresDisplay
            //replacedetBundles --> we already check if file exists while opening it

            //pathAttributes
            bool CheckIfPathAttributeExists(string attribute, ControlPanel.JsonData.PathAttribute[] pathAttributes) {
                for (int i = 0; i < pathAttributes.Length; i++) {
                    if (pathAttributes[i].name == attribute)
                        return true;
                }
                return false;
            }

            if (data.pathAttributeUsedAs_id != "" && !CheckIfPathAttributeExists(data.pathAttributeUsedAs_id, data.pathAttributes)) {
                MakeWarningWindow("The path attribute to use as id doesn't exist");
            }
            if (data.pathAttributeUsedAs_n_atoms != "" && !CheckIfPathAttributeExists(data.pathAttributeUsedAs_n_atoms, data.pathAttributes)) {
                MakeWarningWindow("The path attribute to use as n_atoms doesn't exist");
            }

            if (data.pathAttributes.Length > 0
                + (data.pathAttributeUsedAs_id == "" ? 0 : 1)
                + (data.pathAttributeUsedAs_n_atoms == "" ? 0 : 1)) {
                MakeWarningWindow("Uncommon: some path attributes are unused, is this intentional?");
            }

            //atomAttributes
            bool CheckIfAtomAttributeExists(string attribute, ControlPanel.JsonData.AtomAttribute[] atomAttributes) {
                for (int i = 0; i < atomAttributes.Length; i++) {
                    if (atomAttributes[i].name == attribute)
                        return true;
                }
                return false;
            }

            if (data.atomAttributeUsedAs_x == "" && data.atomAttributeUsedAs_y == "" && data.atomAttributeUsedAs_z == "") {
                MakeErrorWindow("No attributes used for any of the 3 dimensions");
                return false;
            }

            if (data.atomAttributeUsedAs_x != "" && !CheckIfAtomAttributeExists(data.atomAttributeUsedAs_x, data.atomAttributes)) {
                MakeWarningWindow("The atom attribute to use as x doesn't exist");
            }
            if (data.atomAttributeUsedAs_y != "" && !CheckIfAtomAttributeExists(data.atomAttributeUsedAs_y, data.atomAttributes)) {
                MakeWarningWindow("The atom attribute to use as y doesn't exist");
            }
            if (data.atomAttributeUsedAs_z != "" && !CheckIfAtomAttributeExists(data.atomAttributeUsedAs_z, data.atomAttributes)) {
                MakeWarningWindow("The atom attribute to use as z doesn't exist");
            }
            if (data.atomAttributeUsedAs_t != "" && !CheckIfAtomAttributeExists(data.atomAttributeUsedAs_t, data.atomAttributes)) {
                MakeWarningWindow("The atom attribute to use as t doesn't exist");
            }
            if (data.atomAttributeUsedAs_color != "" && !CheckIfAtomAttributeExists(data.atomAttributeUsedAs_color, data.atomAttributes)) {
                MakeWarningWindow("The atom attribute to use as color doesn't exist");
            }

            for (int i = 0; i < data.atomAttributes.Length; i++) {
                CheckValues_swap(ref data.atomAttributes[i].valueColorStart, ref data.atomAttributes[i].valueColorStart, "valueColorStart is bigger than valuecolorEnd for atom attribute " + data.atomAttributes[i].name);
            }

            return true;
        }

19 Source : Util.cs
with MIT License
from anastasios-stamoulis

public static int argmax<T>(T[] values) where T: IComparable {
      if ( values==null ) { return -1; }
      if ( values.Length<=1 ) { return 0; }
      var max_value = values[0];
      var max_index = 0;
      for (int i=1; i<values.Length; i++) {
        if ( values[i].CompareTo(max_value)>0 ) {
          max_index = i;
          max_value = values[i];
        }
      }
      return max_index;
    }

19 Source : MiniHeap.cs
with GNU General Public License v3.0
from AntoineCrb

public void Add(T ele, bool sort = true)
        {
            if ((_size + 1) == _capacity)
            {
                IncreaseCapacity();
            }

            if (!sort || _size == 0)
            {
                _array[_size++] = ele;
                return;
            }

            int min = 0,
                max = _size,
                index = -1;
            while (index == -1)
            {
                int half = (int) Math.Floor((min + max) / 2D);
                int r = ele.CompareTo(_array[half]);
                if (r == 0 || (max - min) == 1)
                {
                    index = max;
                }
                else if (r < 0)
                {
                    max = half;
                }
                else if (r > 0)
                {
                    min = half;
                }
            }

            _size++;
            T tmp = _array[index];
            _array[index] = ele;
            int n = index + 1;
            while (n < _size)
            {
                T tmp2 = _array[n];
                _array[n++] = tmp;
                tmp = tmp2;
            }
        }

19 Source : Enumeration.cs
with GNU General Public License v3.0
from AnyStatus

public int CompareTo(TEnumeration other)
        {
            return Value.CompareTo(other == default(TEnumeration) ? default : other.Value);
        }

19 Source : Atomic.cs
with Apache License 2.0
from apache

public bool CompareAndSet(T expected, T newValue)
        {
            lock (this)
            {
                if (0 == atomicValue.CompareTo(expected))
                {
                    atomicValue = newValue;
                    return true;
                }

                return false;
            }
        }

19 Source : ComparableValue.cs
with MIT License
from appie2go

public int CompareTo(ComparableValue<T> other)
        {
            var comparable = this._value as IComparable;
            if (comparable == null)
            {
                throw new NotSupportedException("Type _value must derive from IComparable to be able to compare it.");
            }

            return comparable.CompareTo(other._value);
        }

19 Source : Utility.cs
with MIT License
from aprilyush

public static int CompareTo(object value1, object value2, out bool success)
        {
            Type type1 = value1.GetType();
            Type type2 = value2.GetType();
            bool isSystemType1 = Type.GetTypeCode(type1) != TypeCode.Object;
            bool isSystemType2 = Type.GetTypeCode(type2) != TypeCode.Object;

            success = false;
            if (isSystemType1)
            {
                //如果value1是基础类型.但两者类型不相同.则将value2转为value1类型
                if (type1 != type2)
                {                    
                    if (type1.IsEnum)
                    {
                        //枚举值.则特殊转换
                        value2 = Utility.ConvertTo(value2.ToString(), type1);
                    }
                    else
                    {
                        if (value2 is IConvertible)
                        {
                            value2 = Utility.ChangeType(value2, type1);
                        }
                        else
                        {
                            value2 = null;
                        }
                    }
                }
            }
            else if (isSystemType2)
            {
                //如果value2是基础类型.但两者类型不相同.则将value1转为value2类型
                if (type1 != type2)
                {
                    if (type2.IsEnum)
                    {
                        //枚举值.则特殊转换
                        value1 = Utility.ConvertTo(value1.ToString(), type2);
                    }
                    else
                    {
                        if (value1 is IConvertible)
                        {
                            value1 = Utility.ChangeType(value1, type2);
                        }
                        else
                        {
                            value1 = null;
                        }
                    }
                }
            }

            if (value1 != null && value1 is IComparable)
            {
                success = true;
                return ((IComparable)value1).CompareTo(value2);
            }
            else if (value2 != null && value2 is IComparable)
            {
                success = true;
                //value2 与 value1相比较.所以结果为相反
                return 0 - ((IComparable)value2).CompareTo(value1);
            }
            return 1;
        }

19 Source : GuardClauseExtensions.cs
with MIT License
from ardalis

private static T Negative<T>([JetBrainsNotNull] this IGuardClause guardClause, T input, [JetBrainsNotNull][JetBrainsInvokerParameterName] string parameterName, string? message = null) where T : struct, IComparable
        {
            if (input.CompareTo(default(T)) < 0)
            {
                throw new ArgumentException(message ?? $"Required input {parameterName} cannot be negative.", parameterName);
            }

            return input;
        }

19 Source : GuardClauseExtensions.cs
with MIT License
from ardalis

private static T NegativeOrZero<T>([JetBrainsNotNull] this IGuardClause guardClause, T input, [JetBrainsNotNull][JetBrainsInvokerParameterName] string parameterName, string? message = null) where T : struct, IComparable
        {
            if (input.CompareTo(default(T)) <= 0)
            {
                throw new ArgumentException(message ?? $"Required input {parameterName} cannot be zero or negative.", parameterName);
            }

            return input;
        }

19 Source : Extensions.cs
with The Unlicense
from astenlund

public static T AdjustToBounds<T>(this T value, T min, T max) where T : IComparable =>
            value.CompareTo(min) < 0
                ? min
                : value.CompareTo(max) > 0
                    ? max
                    : value;

19 Source : EnumerableExtensions.cs
with GNU General Public License v3.0
from atomex-me

public static T MaxBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector)
            where TKey : IComparable
        {
            var maxElement = source.First();
            var maxKey = selector(maxElement);

            foreach (var element in source)
            {
                var key = selector(element);
                if (key.CompareTo(maxKey) > 0)
                {
                    maxElement = element;
                    maxKey = key;
                }
            }

            return maxElement;
        }

19 Source : WebApiArg.cs
with MIT License
from Avanade

private string CreateNameValue(string name, object? value, bool isClreplacedAllowed)
        {
            if (value == null)
                return UriFormat(name, null);

            if (value is string str)
                return UriFormat(name, str);

            if (value is DateTime dt)
                return UriFormat(name, dt.ToString("o", System.Globalization.CultureInfo.InvariantCulture));

            TypeInfo ti = value.GetType().GetTypeInfo();
            if (ti.IsEnum || ti.IsValueType)
                return UriFormat(name, value.ToString());

            if (ti.IsClreplaced)
            {
                if (!isClreplacedAllowed)
                    ThrowComplexityException(ti);

                var sb = new StringBuilder();
                foreach (var pi in ti.DeclaredProperties.Where(x => x.CanRead && x.CanWrite))
                {
                    // Only support serialization of JsonProperty's.
                    var jpa = pi.GetCustomAttribute<JsonPropertyAttribute>(true);
                    if (jpa == null)
                        continue;

                    // Ignore nulls.
                    object pVal = pi.GetValue(value);
                    if (pVal == null)
                        continue;

                    // Define name, and out strings directly.
                    string pName = ArgType == WebApiArgType.FromUriUseProperties ? jpa.PropertyName! : name + "." + jpa.PropertyName;
                    if (pVal is string pstr)
                    {
                        UriAppend(sb, UriFormat(pName, pstr));
                        continue;
                    }

                    // Iterate enumerables where they contain non-clreplaced types only.
                    if (pVal is IEnumerable enumerable)
                    {
                        foreach (var item in enumerable)
                        {
                            if (item != null)
                                UriAppend(sb, CreateNameValue(pName, item, false));
                        }

                        continue;
                    }

                    // Ignore default values.
                    var pti = pi.PropertyType.GetTypeInfo();
                    if (pti.IsValueType || pti.IsEnum)
                    {
                        object defaultValue = Activator.CreateInstance(pi.PropertyType);
                        if (defaultValue is IComparable comparer && comparer.CompareTo(pVal) == 0)
                            continue;
                    }
                    else
                    {
                        var waafa = pi.GetCustomAttribute<WebApiArgFormatterAttribute>();
                        if (waafa != null)
                        {
                            var converter = (IPropertyMapperConverter)Activator.CreateInstance(waafa.ConverterType);
                            if (converter.SrceType != pi.PropertyType || converter.DestType != typeof(string))
                                throw new InvalidOperationException($"Converter Type '{waafa.ConverterType.Name}' must have SrceType of '{pi.PropertyType.Name}' and DestType of 'string'.");

                            UriAppend(sb, CreateNameValue(pName, converter.ConvertToDest(pVal), false));
                            continue;
                        }

                        ThrowComplexityException(ti);
                    }

                    UriAppend(sb, UriFormat(pName, pVal is DateTime dt2 ? dt2.ToString("o", System.Globalization.CultureInfo.InvariantCulture) : pVal.ToString()));
                }

                return sb.ToString();
            }

            return string.Format(System.Globalization.CultureInfo.InvariantCulture, QueryStringFormat, base.Name, Uri.EscapeDataString(value.ToString()));
        }

19 Source : Comparer.cs
with GNU Lesser General Public License v2.1
from axiom3d

public int Compare (object a, object b)
		{
			if (a == b)
				return 0;
			else if (a == null)
				return -1;
			else if (b == null)
				return 1;

			if (m_compareInfo != null) {
				string sa = a as string;
				string sb = b as string;
				if (sa != null && sb != null)
					return m_compareInfo.Compare (sa, sb);
			}

			if (a is IComparable)
				return (a as IComparable).CompareTo (b);
			else if (b is IComparable)
				return -(b as IComparable).CompareTo (a);

			throw new ArgumentException (Locale.GetText ("Neither 'a' nor 'b' implements IComparable."));
        }

19 Source : ValueRangeTextBox.cs
with MIT License
from ay2015

private void ValidateValueInRange(object minValue, object maxValue, object value)
		{
			if (!IsValueNull(value))
			{
				Type type = ValueDataType;
				if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
				{
					NullableConverter nullableConverter = new NullableConverter(type);
					type = nullableConverter.UnderlyingType;
				}
				if (value.GetType() != type)
				{
					value = Convert.ChangeType(value, type);
				}
				if (minValue != null)
				{
					IComparable comparable = (IComparable)minValue;
					if (maxValue != null && comparable.CompareTo(maxValue) > 0)
					{
						throw new ArgumentOutOfRangeException("minValue", "MaxValue must be greater than MinValue.");
					}
					if (comparable.CompareTo(value) > 0)
					{
						throw new ArgumentOutOfRangeException("minValue", "Value must be greater than MinValue.");
					}
				}
				if (maxValue != null)
				{
					IComparable comparable2 = (IComparable)maxValue;
					if (comparable2.CompareTo(value) < 0)
					{
						throw new ArgumentOutOfRangeException("maxValue", "Value must be less than MaxValue.");
					}
				}
			}
		}

19 Source : ComparisonBinding.cs
with MIT License
from ay2015

public object Convert(

            object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

        {

            // Simple check for null



            if (value == null || _styleBinding.Comparand == null)

            {

                return ReturnHelper(value == _styleBinding.Comparand);

            }



            // Convert the comparand so that it matches the value



            object convertedComparand = _styleBinding.Comparand;

            try

            {

                // Only support simple conversions in here. 

                convertedComparand = System.Convert.ChangeType(_styleBinding.Comparand, value.GetType());

            }

            catch (InvalidCastException)

            {

                // If Convert.ChangeType didn’t work, try a type converter

                TypeConverter typeConverter = TypeDescriptor.GetConverter(value);

                if (typeConverter != null)

                {

                    if (typeConverter.CanConvertFrom(_styleBinding.Comparand.GetType()))

                    {

                        convertedComparand = typeConverter.ConvertFrom(_styleBinding.Comparand);

                    }

                }

            }



            // Simple check for the equality case



            if (_styleBinding.Operator == ComparisonOperators.eq)

            {

                // Actually, equality is a little more interesting, so put it in

                // a helper routine



                return ReturnHelper(

                            CheckEquals(value.GetType(), value, convertedComparand));

            }



            // For anything other than Equals, we need IComparable



            if (!(value is IComparable) || !(convertedComparand is IComparable))

            {

                Trace(value, "One of the values was not an IComparable");

                return ReturnHelper(false);

            }



            // Compare the values



            int comparison = (value as IComparable).CompareTo(convertedComparand);



            // And return the comparisson result



            switch (_styleBinding.Operator)

            {

                case ComparisonOperators.g:

                    return ReturnHelper(comparison > 0);



                case ComparisonOperators.ge:

                    return ReturnHelper(comparison >= 0);



                case ComparisonOperators.l:

                    return ReturnHelper(comparison < 0);



                case ComparisonOperators.le:

                    return ReturnHelper(comparison <= 0);

            }



            return _notNull;

        }

19 Source : Doc.Validation.cs
with MIT License
from azist

protected virtual Exception CheckValueMinMax(string targetName, Schema.FieldDef fdef, FieldAttribute atr, object value, string scope)
    {
      if (!(value is IComparable val)) return null;

      if (atr.Min != null)
      {
        var bound = atr.Min as IComparable;
        if (bound != null)
        {
            var tval = val.GetType();

            bound = Convert.ChangeType(bound, tval) as IComparable;

            if (val.CompareTo(bound)<0)
                return new FieldValidationException(Schema.DisplayName, fdef.Name, StringConsts.CRUD_FIELD_VALUE_MIN_BOUND_ERROR);
        }
      }

      if (atr.Max != null)
      {
        var bound = atr.Max as IComparable;
        if (bound != null)
        {
            var tval = val.GetType();

            bound = Convert.ChangeType(bound, tval) as IComparable;

            if (val.CompareTo(bound)>0)
                return new FieldValidationException(Schema.DisplayName, fdef.Name, StringConsts.CRUD_FIELD_VALUE_MAX_BOUND_ERROR);
        }
      }

      return null;
    }

19 Source : Rowset.cs
with MIT License
from azist

public override int Compare(Doc docA, Doc docB)
    {
      if (docA == null && docB != null) return -1;

      if (docA != null && docB == null) return 1;

      if (docA == null && docB == null) return 0;

      if (object.ReferenceEquals(docA, docB)) return 0;

      if (docA.Schema != docB.Schema) return 1;


      foreach (var sortDef in m_SortFieldList)
      {
        var sfld = sortDef.Trim();

        var desc = false;
        if (sfld.StartsWith("+"))
          sfld = sfld.Remove(0, 1);

        if (sfld.StartsWith("-"))
        {
          sfld = sfld.Remove(0, 1);
          desc = true;
        }

        var fld = m_Schema[sfld];
        if (fld == null) return 1;//safeguard

        var obj1 = docA[fld.Order] as IComparable;
        var obj2 = docB[fld.Order] as IComparable;

        if (obj1 == null && obj2 == null) continue;
        if (obj1 == null) return desc ? 1 : -1;
        if (obj2 == null) return desc ? -1 : 1;

        var result = desc ? -obj1.CompareTo(obj2) : obj1.CompareTo(obj2);
        if (result != 0) return result;
      }
      return 0;
    }

19 Source : Table.cs
with MIT License
from azist

public static int CompareRows(Schema schema, Doc rowA, Doc rowB)
    {
      if (rowA == null && rowB != null) return -1;

      if (rowA != null && rowB == null) return 1;

      if (rowA == null && rowB == null) return 0;

      if (object.ReferenceEquals(rowA, rowB)) return 0;

      if (rowA.Schema != rowB.Schema) return 1;


      foreach (var fld in schema.AnyTargetKeyFieldDefs)
      {
        var obj1 = rowA[fld.Order] as IComparable;
        var obj2 = rowB[fld.Order] as IComparable;

        if (obj1 == null && obj2 == null) continue;
        if (obj1 == null) return -1;
        if (obj2 == null) return +1;

        var result = obj1.CompareTo(obj2);
        if (result != 0) return result;
      }

      return 0;
    }

19 Source : CollectionUtils.cs
with MIT License
from azist

private static TResult firstMinMax<TResult, TComparand>(bool min,
                                                        IEnumerable<TResult> source,
                                                        Func<TResult, TComparand> selector,
                                                        out TComparand latchedComparand) where TComparand: IComparable
    {
      var latchedResult = default(TResult);
      latchedComparand = default(TComparand);

      if (source==null || selector==null) return latchedResult;

      bool was = false;
      foreach(var elm in source)
      {
        var c = selector(elm);
        if (!was || (min ? c.CompareTo(latchedComparand)<0 : c.CompareTo(latchedComparand)>0))
        {
          latchedResult = elm;
          latchedComparand = c;
          was = true;
        }
      }

      return latchedResult;
    }

19 Source : RadioGroupElement.cs
with MIT License
from azist

private bool equal(object o1, object o2)
         {
           if ((o1==null)||(o2==null))
              return false;

           if (o1.GetType() != o2.GetType())
              return false;

           if (o1 is IComparable)
            return ((IComparable) o1).CompareTo(o2) == 0;

           return false;
         }

19 Source : ArrayExt.cs
with MIT License
from baba-s

public static void Sort<TSource, TResult>( this TSource[] array, Func<TSource, TResult> selector ) where TResult : IComparable
		{
			Array.Sort( array, ( x, y ) => selector( x ).CompareTo( selector( y ) ) );
		}

19 Source : ArrayExt.cs
with MIT License
from baba-s

public static void SortDescending<TSource, TResult>( this TSource[] array, Func<TSource, TResult> selector ) where TResult : IComparable
		{
			Array.Sort( array, ( x, y ) => selector( y ).CompareTo( selector( x ) ) );
		}

19 Source : ArrayExt.cs
with MIT License
from baba-s

public static void Sort<TSource, TResult>( this TSource[] array, Func<TSource, TResult> selector1, Func<TSource, TResult> selector2 ) where TResult : IComparable
		{
			Array.Sort( array, ( x, y ) =>
			{
				var result = selector1( x ).CompareTo( selector1( y ) );
				return result != 0 ? result : selector2( x ).CompareTo( selector2( y ) );
			} );
		}

19 Source : ListExt.cs
with MIT License
from baba-s

public static void Sort<TSource, TResult1, TResult2>( this List<TSource> self, Func<TSource, TResult1> selector1, Func<TSource, TResult2> selector2 ) where TResult1 : IComparable where TResult2 : IComparable
		{
			self.Sort( ( x, y ) =>
			{
				var result = selector1( x ).CompareTo( selector1( y ) );
				return result != 0 ? result : selector2( x ).CompareTo( selector2( y ) );
			} );
		}

19 Source : ListExt.cs
with MIT License
from baba-s

public static void SortDescending<TSource, TResult>( this List<TSource> self, Func<TSource, TResult> selector ) where TResult : IComparable
		{
			self.Sort( ( x, y ) => selector( y ).CompareTo( selector( x ) ) );
		}

19 Source : ListExt.cs
with MIT License
from baba-s

public static void SortDescending<TSource, TResult1, TResult2>( this List<TSource> self, Func<TSource, TResult1> selector1, Func<TSource, TResult2> selector2 ) where TResult1 : IComparable where TResult2 : IComparable
		{
			self.Sort( ( x, y ) =>
			{
				var result = selector1( y ).CompareTo( selector1( x ) );
				return result != 0 ? result : selector2( x ).CompareTo( selector2( y ) );
			} );
		}

19 Source : ListExt.cs
with MIT License
from baba-s

public static void Sort<TSource, TResult>( this List<TSource> self, Func<TSource, TResult> selector ) where TResult : IComparable
		{
			self.Sort( ( x, y ) => selector( x ).CompareTo( selector( y ) ) );
		}

19 Source : Check.cs
with MIT License
from BEagle1984

public static T Range<T>(T value, string parameterName, T min, T max)
            where T : struct, IComparable
        {
            if (value.CompareTo(min) < 0 || value.CompareTo(max) > 0)
            {
                NotEmpty(parameterName, nameof(parameterName));

                throw new ArgumentOutOfRangeException(
                    parameterName,
                    $"The value must be between {min} and {max}.");
            }

            return value;
        }

19 Source : MultiComparer.cs
with Apache License 2.0
from beckzhu

private static FuncComparer<TObject> BuildAscendingComparer<TAttribute>(Func<TObject, TAttribute> accessor)
             where TAttribute : IComparable
        {
            //TODO handle ref types better
            return new FuncComparer<TObject>((x, y) => accessor(x).CompareTo(accessor(y)));
            
        }

19 Source : MultiComparer.cs
with Apache License 2.0
from beckzhu

private static FuncComparer<TObject> BuildDescendingComparer<TAttribute>(Func<TObject, TAttribute> accessor)
            where TAttribute : IComparable
        {
            //TODO handle ref types better
            return new FuncComparer<TObject>((x, y) => accessor(y).CompareTo(accessor(x)));
        }

19 Source : AcceptableValueRange.cs
with GNU Lesser General Public License v2.1
from BepInEx

public override object Clamp(object value)
        {
            if (MinValue.CompareTo(value) > 0)
                return MinValue;

            if (MaxValue.CompareTo(value) < 0)
                return MaxValue;

            return value;
        }

See More Examples