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?
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With