C#: Getting maximum and minimum values of arbitrary properties of all items in a list

前端 未结 8 1602
温柔的废话
温柔的废话 2021-02-02 13:19

I have a specialized list that holds items of type IThing:

public class ThingList : IList
{...}

public interface IThing
{
    Decimal         


        
相关标签:
8条回答
  • 2021-02-02 14:04

    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; });
    
    0 讨论(0)
  • 2021-02-02 14:09

    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; });
    
    0 讨论(0)
提交回复
热议问题