I have a function to return minimum of n numbers. Code given below:
=====[ CODE ]===============================
private int FindMinimum(int[] numbers)
{
int temp, i;
temp = 0;
for (i=0; i<= numbers.length; i++)
{
temp = Math.Min(temp, numbers[i]);
}
return temp;
}
==========================================
I have not checked the above code. I actually want that the return
type be generic, so that I can use this function for int, double or
decimal. How to modify the above function to use generic return type?
Jeroen Mostert - 17 Feb 2008 14:25 GMT
> I have a function to return minimum of n numbers. Code given below:
>
[quoted text clipped - 14 lines]
> type be generic, so that I can use this function for int, double or
> decimal. How to modify the above function to use generic return type?
private static T FindMinimum<T>(IEnumerable<T> collection, T
identityElement) where T : IComparable<T> {
T min = identityElement;
foreach (T t in collection) {
if (t.CompareTo(min) < 0) min = t;
}
return min;
}
Sample use:
FindMinimum(new int[] { 2, 3, 1 }, Int.MaxValue) == 1
FindMinimum(new int[] { }, Int.MaxValue) == Int.MaxValue
You can leave out the "identity element" thing and restrict the function to
operate on non-empty collections only, but that's not as concise:
private static T FindMinimum<T>(IEnumerable<T> collection) where T :
IComparable<T> {
IEnumerator<T> enumerator = collection.GetEnumerator();
if (!enumerator.MoveNext()) throw new ArgumentException("Attempt to
find the minimum of an empty collection.");
T min = enumerator.Current;
while (enumerator.MoveNext()) {
if (enumerator.Current.CompareTo(min) < 0) min = enumerator.Current;
}
return min;
}

Signature
J.
Marc Gravell - 17 Feb 2008 19:02 GMT
It is worth mentioning that .NET 3.5 provides this functionality "out
of the box" via Enumerable.Min<T>() etc. Also, Comparer<T>.Default can
be used if you don't want to enforce the constraint in the API; while
constraints are a good thing, the downside is that it tends to
snowball, so higher up functions end up with 3 or 4 constraints that
are only used in edge-cases. This approach [Comparer<T>.Default, no
constraint] is what LINQ uses (.NET 3.5).
Marc