IComparable interface for partial ordering
I am trying to define a generic function to give the largest value for a set of parameters. It works 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 screeches on the "item> result" line. I need a way to restrict the TResult to have the> operator (or <will work too.) However, I don't see any interface available to do this. Since this is a partial ordering, this seems like a fairly common task. Am I missing something in the giant .NET documentation?
source to share
There is no interface that only supports partial ordering. You also cannot use operators in generics.
The most common solution is to pass a comparator method delegate.
You can also use only part of the tags IComparable
or IComparer
that say "this is more than this" and ignore the other 2 values.
IComparable
and
IComparer<in T>
that is used via LINQ queries. That is, see OrderBy .
source to share