I have a specialized list that holds items of type IThing
:
public class ThingList : IList
{...}
public interface IThing
{
Decimal
Here's an attempt, using C# 2.0, at Skilwz's idea.
public delegate T GetPropertyValueDelegate<T>(IThing t);
public T GetMaximum<T>(GetPropertyValueDelegate<T> getter)
where T : IComparable
{
if (this.Count == 0) return default(T);
T max = getter(this[0]);
for (int i = 1; i < this.Count; i++)
{
T ti = getter(this[i]);
if (max.CompareTo(ti) < 0) max = ti;
}
return max;
}
You'd use it like this:
ThingList list;
Decimal maxWeight = list.GetMaximum(delegate(IThing t) { return t.Weight; });
Conclusion: There is no better way for .Net 2.0 (with Visual Studio 2005).
You seem to have misunderstood the answers (especially Jon's). You can use option 3 from his answer. If you don't want to use LinqBridge you can still use a delegate and implement the Max
method yourself, similar to the method I've posted:
delegate Decimal PropertyValue(IThing thing);
public class ThingList : IList<IThing> {
public Decimal Max(PropertyValue prop) {
Decimal result = Decimal.MinValue;
foreach (IThing thing in this) {
result = Math.Max(result, prop(thing));
}
return result;
}
}
Usage:
ThingList lst;
lst.Max(delegate(IThing thing) { return thing.Age; });