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

前端 未结 8 1610
温柔的废话
温柔的废话 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(IThing t);
    
    public T GetMaximum(GetPropertyValueDelegate 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; });
    

提交回复
热议问题