How do I use the IComparable interface?

后端 未结 6 407
后悔当初
后悔当初 2021-02-02 13:40

I need a basic example of how to use the IComparable interface so that I can sort in ascending or descending order and by different fields of the object type I\'m s

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-02 14:22

    This might not be in relation to sorting order, but it is still - I think - an interesting use of IComparable:

    public static void MustBeInRange(this T x, T minimum, T maximum, string paramName)
    where T : IComparable
    {
        bool underMinimum = (x.CompareTo(minimum) < 0);
        bool overMaximum = (x.CompareTo(maximum) > 0);
        if (underMinimum || overMaximum)
        {
            string message = string.Format(
                System.Globalization.CultureInfo.InvariantCulture,
                "Value outside of [{0},{1}] not allowed/expected",
                minimum, maximum
            );
            if (string.IsNullOrEmpty(paramName))
            {
                Exception noInner = null;
                throw new ArgumentOutOfRangeException(message, noInner);
            }
            else
            {
                throw new ArgumentOutOfRangeException(paramName, x, message);
            }
        }
    }
    
    public static void MustBeInRange(this T x, T minimum, T maximum)
    where T : IComparable { x.MustBeInRange(minimum, maximum, null); }
    

    These simple extension methods allow you to do parameter range checking for any type that implements IComparable like this:

    public void SomeMethod(int percentage, string file) {
        percentage.MustBeInRange(0, 100, "percentage");
        file.MustBeInRange("file000", "file999", "file");
        // do something with percentage and file
        // (caller will have gotten ArgumentOutOfRangeExceptions when applicable)
    }
    

提交回复
热议问题