Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IComparable type interface for partial ordering

I am trying to define a generic function to give the largest value of a set of parameters. It goes like this:

    public static TResult Max<TResult>(params TResult[] items)
    {
        TResult result = items[0];
        foreach (var item in items)
        {
            if (item > result)
                result = item;
        }
        return result;
    }

This is all well and good, except that the compiler croaks on the "item > result" line. What I need is a way to constrain the TResult to have a > operator (or < would work too.) However, I don't see any readily available interface to do this. Since this is partial ordering it seems a pretty common task. Am I missing something in the gigantic .NET documentation?

like image 514
Jessica Boxer Avatar asked Oct 12 '25 08:10

Jessica Boxer


2 Answers

You could use IComparable:

public static IComparable Max<TResult>(params IComparable[] items)
{
    IComparable result = items[0];
    foreach (var item in items)
    {
        if (item.CompareTo(result) > 0)
            result = item;
    }
    return result;
}
like image 124
Tudor Avatar answered Oct 13 '25 21:10

Tudor


There is no interface that suppport just partial ordering. You can't also use operators in generics.

Most common solution - pass comparator method delegate.

You can also use just part of IComparable or IComparer intefaces that says "this is grater thant that" and ignore 2 other values.

IComparable and IComparer<in T> that is used through LINQ queries. I.e. see OrderBy.

like image 28
Alexei Levenkov Avatar answered Oct 13 '25 21:10

Alexei Levenkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!